我尝试绘制一些形状,我需要添加更改颜色作为选择复选框的事件。当我选择复选框时,如何编写将改变颜色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;
}
};
答案 0 :(得分:5)
您可以将一个ActionListener添加到JCheckBox,它只是在绘图JComponent上调用repaint()
。然后在paintComponent中,通过调用复选框的isSelected()
来检查复选框的状态,并将颜色基于布尔结果。
Color tmp = redBtn.isSelected() ? SELECTED_COLOR : null;