我想在按下按钮时重新绘制一个圆圈。
目前,无论何时按下按钮,我都会按下按钮,它会向控制台输出我按下的按钮。例如,如果我按下#34; Paint Red"按钮,我希望它用红色填充圆圈,并且与其他颜色相同。我试图围绕整个paint / paintComponent的差异。
这就是我到目前为止......
public class testCircle extends JPanel {
public void paint(Graphics g)
{
setSize(500,500);
int R = (int) (Math.random( )*256);
int G = (int)(Math.random( )*256);
int B= (int)(Math.random( )*256);
Color randomColor = new Color(R, G, B);
g.setColor(randomColor);
g.drawOval(75, 100, 200,200);
g.fillOval(75, 100, 200, 200);
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(400, 400);
testCircle circlePanel = new testCircle();
frame.add(circlePanel);
JButton redButton = new JButton("Paint Red");
redButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event)
{
System.out.println("Red Button Pressed!");
}
});
JButton blueButton = new JButton("Paint Blue");
blueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event)
{
System.out.println("Blue Button Pressed!");
}
});
JButton greenButton = new JButton("Paint Green");
greenButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event)
{
System.out.println("Green Button Pressed!");
}
});
redButton.setPreferredSize(new Dimension(100,100));
blueButton.setPreferredSize(new Dimension(100,100));
greenButton.setPreferredSize(new Dimension(100,100));
frame.setLayout(new FlowLayout());
frame.add(redButton);
frame.add(blueButton);
frame.add(greenButton);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
答案 0 :(得分:3)
考虑对代码的这些更改:
正如所讨论的here,Swing程序应覆盖paintComponent()
而不是覆盖paint()
。
为您的小组提供currentColor
的属性。
private Color currentColor;
让每个按钮ActionListener
设置currentColor
并调用repaint()
。
currentColor = color;
repaint();
使用Action
来封装程序的功能。
检查完整的示例here。
答案 1 :(得分:0)
您不会在代码中的任何位置触发“重绘”。这应该有效:
redButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("Red Button Pressed!");
frame.invalidate();
frame.validate();
}
});