1

我尝试绘制一些形状,我需要添加更改颜色作为选择复选框的事件。如何编写tmp当我选择复选框时会改变颜色的新方法?

我创建 JCheckBox 的方法:

public class Paint extends JFrame {
public Paint() {

    JCheckBox redBtn = new JCheckBox("Red");

}

}

绘制矩形颜色的方法:

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);
        }
    }

编辑:

ActionListener 应该是这样的吗?

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

1 回答 1

5

您可以向 JCheckBox 添加一个 ActionListener,它只调用repaint()绘图 JComponent。然后在paintComponent 内部,通过调用它来检查复选框的状态isSelected(),并将您的颜色基于布尔结果。

Color tmp = redBtn.isSelected() ? SELECTED_COLOR : null;
于 2012-06-01T21:20:59.020 回答