我试图更好地理解Java中的GUI编程,但出现了一些奇怪的行为。该程序显示一个具有随机颜色渐变的圆,当您单击按钮时,颜色会发生变化。非常简单,除了我注意到当我意外地扩展窗口时,actionPerformed被触发,并且按钮会不断地改变颜色,就像我在按下按钮一样。我的问题是为什么会发生这种情况?我正在使用Windows环境,如果这很重要的话。我的代码:
public class SimpleGui3C implements ActionListener {
JFrame frame;
public static void main (String[] args) {
SimpleGui3C gui = new SimpleGui3C();
gui.go();
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Change Colors");
button.addActionListener(this);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH, button);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setSize(300, 300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
frame.repaint();
}
}
MyDrawPanel
class MyDrawPanel extends JPanel {
@Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
int red = (int) (Math.random() * 256);
int green = (int) (Math.random() * 256);
int blue = (int) (Math.random() * 256);
Color startColor = new Color(red, green, blue);
red = (int) (Math.random() * 256);
green = (int) (Math.random() * 256);
blue = (int) (Math.random() * 256);
Color endColor = new Color(red, green, blue);
GradientPaint gradient = new GradientPaint(70,70,startColor, 150,150, endColor);
g2d.setPaint(gradient);
g2d.fillOval(70,70,100,100);
}
}
https://stackoverflow.com/questions/50710716
复制相似问题