14. 8. 2. JToggleButton is a button that has two states. Pressed and not pressed.

 

 

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JToggleButton;

public class ToggleButton extends JDialog implements ActionListener {

  private JToggleButton red = new JToggleButton("red");

  private JToggleButton green = new JToggleButton("green");

  private JToggleButton blue = new JToggleButton("blue");

  private JPanel display = new JPanel();

  public ToggleButton() {
    JPanel bottom = new JPanel();
    JPanel leftPanel = new JPanel();

    red.addActionListener(this);
    green.addActionListener(this);
    blue.addActionListener(this);

    leftPanel.add(red);
    leftPanel.add(green);
    leftPanel.add(blue);
    bottom.add(leftPanel);

    display.setBackground(Color.black);

    bottom.add(display);
    add(bottom);

    pack();
    setResizable(false);
    setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    setVisible(true);
  }

  public static void main(String[] args) {
    new ToggleButton();
  }

  public void actionPerformed(ActionEvent e) {
    Color color = display.getBackground();
    int red = color.getRed();
    int green = color.getGreen();
    int blue = color.getBlue();

    if (e.getActionCommand() == "red") {
      if (red == 0) {
        red = 255;
      } else {
        red = 0;
      }
    }

    if (e.getActionCommand() == "green") {
      if (green == 0) {
        green = 255;
      } else {
        green = 0;
      }
    }

    if (e.getActionCommand() == "blue") {
      if (blue == 0) {
        blue = 255;
      } else {
        blue = 0;
      }
    }

    Color setCol = new Color(red, green, blue);
    display.setBackground(setCol);
  }
}


 

你可能感兴趣的:(String,Class,import,button)