简体   繁体   中英

How to add event to checkbox?

I try to painting some shapes and I need to add changing colors as an event of select checkbox. How to write new method which will change color tmp when I select checkbox ?

Method where I create JCheckBox:

public class Paint extends JFrame {
public Paint() {

    JCheckBox redBtn = new JCheckBox("Red");

}

}

Method where is color of painted rectangle:

private class PaintSurface extends JComponent {
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        Color tmp = null;   //If no checkbox selected, no color

        for (Shape s : shapes) 
            g2.setPaint(tmp);  //Here is color of shape
            g2.fill(s);
        }
    }

EDIT:

This is how ActionListener should looks like?

ActionListener actionListener = new ActionListener() {
              public void actionPerformed(ActionEvent actionEvent) {
                  JCheckBox a = (JCheckBox) actionEvent.getSource();
                 Color tmp = redBtn.isSelected() ? Color.RED : null;
              }
};

You could add an ActionListener to the JCheckBox which simply calls repaint() on the drawing JComponent. Then inside paintComponent, check the state of the check box by calling isSelected() on it, and base your Color on the boolean result.

Color tmp = redBtn.isSelected() ? SELECTED_COLOR : null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM