我在跨 JPanel 移动这个 JLabel 时遇到问题?我把代码放在下面。基本上应该发生的是名为“guy”的 JLabel 慢慢向右移动。唯一的问题是,JLabel 没有刷新,它在我第一次移动它后就消失了。
public class Window extends JFrame{
JPanel panel = new JPanel();
JLabel guy = new JLabel(new ImageIcon("guy.gif"));
int counterVariable = 1;
//Just the constructor that is called once to set up a frame.
Window(){
super("ThisIsAWindow");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(panel);
panel.setLayout(null);
}
//This method is called once and has a while loop to exectue what is inside.
//This is also where "counterVariable" starts at zero, then gradually
//goes up. The variable that goes up is suposed to move the JLabel "guy"...
public void drawWorld(){
while(true){
guy.setBounds(counterVariable,0,50,50);
panel.add(guy);
counterVarialbe++;
setVisible(true);
try{Thread.sleep(100)}catch(Exception e){}
}
}
关于为什么在我更改变量“counterVariable”后 JLabel 只是消失而不是向右移动的任何想法。 -谢谢! :)
最佳答案
您的代码导致一个长时间运行的进程在 Swing 事件线程上运行,这阻止了该线程执行其必要的操作:绘制 GUI 和响应用户输入。这将有效地让您的整个 GUI 进入 hibernate 状态。
问题与建议:
- 永远不要在 Swing 事件调度线程或 EDT 上调用
Thread.sleep(...)
。 - 永远不要在 EDT 上使用
while (true)
。 - 改为使用 Swing Timer对于所有这些。
- 无需继续将 JLabel 添加到 JPanel。添加到 JPanel 后,它会保留在那里。
- 同样,无需在 JLabel 上继续调用
setVisible(true)
。一旦可见,它就会一直可见。 - 在移动 JLabel 后,在容器上调用
repaint()
以请求重新绘制容器及其子项。
例如,
public void drawWorld(){
guy.setBounds(counterVariable,0,50,50);
int timerDelay = 100;
new javax.swing.Timer(timerDelay, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
countVariable++;
guy.setBounds(counterVariable,0,50,50);
panel.repaint();
}
}).start;
}
警告:代码未以任何方式编译、运行或测试
关于java - 刷新 JPanel-移动 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11068535/