[英]JFrame doesn't repaint
I have a JFrame , which has a JPanel and a JButton . 我有一个JFrame,其中有一个JPanel和JButton。 The JFrame is set to BorderLayout , and i expected my code to repaint the panel every 500 millisecs after the button has been clicked. JFrame设置为BorderLayout,我希望我的代码在单击按钮后每500毫秒重新绘制一次面板。 But even though the setup goes into a loop , the frame does not repaint. 但是,即使设置进入循环,该框架也不会重新绘制。
Here is what i wrote for when the button is clicked 这是我在单击按钮时写的内容
public void actionPerformed(ActionEvent e) {
while(true){
try {
frame.repaint(); // does not repaint
Thread.sleep(500);
} catch (InterruptedException exp) {
exp.printStackTrace();
}
}
}
and this for the setup : 这是安装程序:
public void go() {
b.addActionListener(new ButtonListener()); // b is the JButton
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // frame is the JFrame
frame.setLayout(new BorderLayout());
frame.add(BorderLayout.CENTER, p); // p is a MyPanel
frame.add(BorderLayout.SOUTH, b);
frame.setSize(300, 300);
frame.setVisible(true);
}
class MyPanel extends JPanel { // p is an instance of this MyPanel class
public void paintComponent(Graphics gr) {
gr.fillRect(0, 0, this.getWidth(), this.getHeight());
int r, g, b, x, y;
r = (int) (Math.random() * 256);
g = (int) (Math.random() * 256);
b = (int) (Math.random() * 256);
x = (int) (Math.random() * (this.getWidth() - 15 ));
y = (int) (Math.random() * (this.getHeight() - 15));
Color customColor = new Color(r, g, b);
gr.setColor(customColor);
gr.fillOval(x, y, 30, 30);
}
}
Your ActionListener
contains 2 surefire mechanisms for blocking a Swing Application - an infinite loop and a Thread.sleep
call. 您的ActionListener
包含2个用于阻止Swing应用程序的surefire机制-无限循环和Thread.sleep
调用。 Use a Swing Timer instead 请改用Swing计时器
Timer timer = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.repaint();
}
});
timer.setRepeats(false);
timer.start();
Code executed from a listener executes on the Event Dispatch Thread (EDT) and the Thread.sleep() is causing the EDT to sleep so the GUI can never repaint itself. 从侦听器执行的代码在事件调度线程(EDT)上执行,并且Thread.sleep()使EDT进入睡眠状态,因此GUI永远无法重新绘制自身。 Don't use Thread.sleep.(). 不要使用Thread.sleep。()。
Instead use a Swing Timer . 而是使用Swing计时器 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.