刷新JPanel - 移动JLabel

时间:2012-06-17 02:39:31

标签: java swing layout jlabel

我无法在此JPanel中移动此JLabel?我把代码放在下面。基本上应该发生的事情是被称为“家伙”的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正在消失而不是向右移动的想法。 -谢谢! :)

1 个答案:

答案 0 :(得分:4)

您的代码导致长时间运行的进程在Swing事件线程上运行,这阻止了此线程执行其必要的操作:绘制GUI并响应用户输入。这将有效地让您的整个GUI处于睡眠状态。

问题&建议:

  • 永远不要在Swing Event Dispatch Thread或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;
}

警告:代码未以任何方式编译,运行或测试