Refreshing a JPanel-Moving a JLabel

懵懂的女人 提交于 2020-01-15 11:28:06

问题


I am having trouble moving this JLabel across this JPanel? I put the code below. Basically what is supposed to happen, is the JLabel called "guy" slowly moves to the right. The only problem is, that the JLabel isn't refreshing it just disappears after the first time I move it.

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){}
        }

    }

Any thoughts as to why the JLabel is just disappearing instead of moving to the right after I change the variable "counterVariable". -Thanks! :)


回答1:


Your code is causing a long-running process to run on the Swing event thread which is preventing this thread from doing its necessary actions: paint the GUI and respond to user input. This will effectively put your entire GUI to sleep.

Issue & suggestions:

  • Never call Thread.sleep(...) on the Swing Event Dispatch Thread or EDT.
  • Never have a while (true) on the EDT.
  • Instead use a Swing Timer for all of this.
  • No need to keep adding the JLabel to the JPanel. Once added to the JPanel, it remains there.
  • Likewise, no need to keep calling setVisible(true) on the JLabel. Once visible, it remains visible.
  • Call repaint() on the container holding the moving JLabel after you've moved it to request that the container and its children be re-drawn.

e.g.,

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;
}

caveat: code not compiled, run, or tested in any way



来源:https://stackoverflow.com/questions/11068535/refreshing-a-jpanel-moving-a-jlabel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!