我有一个JFrame,它有一个JPanel和一个JButton。 JFrame设置为BorderLayout,我希望我的代码在单击按钮后每500毫秒重新绘制一次面板。但即使设置进入循环,框架也不会重新绘制。
以下是我点击按钮时所写的内容
public void actionPerformed(ActionEvent e) {
while(true){
try {
frame.repaint(); // does not repaint
Thread.sleep(500);
} catch (InterruptedException exp) {
exp.printStackTrace();
}
}
}
这适用于设置:
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);
}
}
答案 0 :(得分:3)
您的ActionListener
包含2个阻止Swing应用程序的可靠机制 - 无限循环和Thread.sleep
调用。请改用Swing Timer
Timer timer = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.repaint();
}
});
timer.setRepeats(false);
timer.start();
答案 1 :(得分:3)
从侦听器执行的代码在Event Dispatch Thread (EDT)上执行,而Thread.sleep()导致EDT进入睡眠状态,因此GUI永远不会自行重绘。不要使用Thread.sleep。()。
而是使用Swing Timer。