首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >展开窗口时触发的actionPerformed

展开窗口时触发的actionPerformed
EN

Stack Overflow用户
提问于 2018-06-06 08:32:19
回答 1查看 26关注 0票数 1

我试图更好地理解Java中的GUI编程,但出现了一些奇怪的行为。该程序显示一个具有随机颜色渐变的圆,当您单击按钮时,颜色会发生变化。非常简单,除了我注意到当我意外地扩展窗口时,actionPerformed被触发,并且按钮会不断地改变颜色,就像我在按下按钮一样。我的问题是为什么会发生这种情况?我正在使用Windows环境,如果这很重要的话。我的代码:

代码语言:javascript
复制
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

代码语言:javascript
复制
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);
}
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50710716

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档