[英]repaint() not being called properly from actionlistener
我的問題是如何讓repaint()在從方法執行時正常工作,或者更具體地說是從actionlistener執行。 為了說明我的觀點,moveIt()方法從初始go()執行時,按預期調用repaint(),你會看到圓形幻燈片。 當從ActionListener按鈕調用moveIt()時,圓圈從開始位置跳到結束位置。 我在調用repaint()之前和repaint()中包含了一個println語句,你可以看到repaint()在啟動時調用了10次,而在按下按鈕時只調用了一次。 - 提前感謝你的幫助。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleAnimation {
int x=70;
int y=70;
MyDrawPanel drawPanel;
public static void main(String[] args) {
SimpleAnimation gui = new SimpleAnimation();
gui.go();
}
public void go(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawPanel = new MyDrawPanel();
JButton button = new JButton("Move It");
frame.getContentPane().add(BorderLayout.NORTH, button);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
button.addActionListener(new ButtonListener());
//frame.getContentPane().add(drawPanel);
frame.setSize(300,300);
frame.setVisible(true);
// frame.pack(); Tried it with frame.pack with same result.
moveIt();
}//close go()
public void moveIt(){
for (int i=0; i<10; i++){
x++;
y++;
drawPanel.revalidate();
System.out.println("before repaint"); //for debugging
drawPanel.repaint();
try{
Thread.sleep(50);
}catch (Exception e){}
}
}//close moveIt()
class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
moveIt();
}
}//close inner class
class MyDrawPanel extends JPanel{
public void paintComponent(Graphics g){
System.out.println("in repaint"); //for debugging
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.blue);
g.fillOval(x, y, 100, 100);
}
}//close inner class
}
您正在EDT(事件調度線程)上執行長時間運行的任務(休眠)。 因此,當EDT處於休眠狀態時,它無法更新UI,並且重新繪制無法按預期工作。
要糾正這種情況,請始終睡在單獨的線程上。
在這種情況下使用SwingWorker或Timer
有關如何以線程安全的方式訪問swing組件的更多信息,請查看此帖子。
更新: 此頁面更好地解釋了它。
在ActionListener
調用Thread.sleep
阻止EDT
並導致GUI“凍結”。 你可以在這里使用Swing計時器 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.