I have a JFrame with a CardLayout component. I am using the CardLayout to switch between different JPanel's at different moments of the application execution. At some point I am using a SwingWorker Object to generate some XML files. In this time I want to display another JPanel in my window to tell the user to wait. On this JPanel I want to switch between 3 labels.

  • JLabel 1 would be : "Please wait."
  • JLabel 2 would be : "Please wait.."
  • JLabel 3 would be : "Please wait..."

Right now the code looks like this:

        ConvertersWorker.execute();
        CLayout.show(Cards, WAIT_PANEL);


        Timer t =new Timer(500, new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e) {
                WaitPanel.SwitchLabels();
            }               
        });
        t.start();

        while (!this.finishedConverting)
        {

        }
        //After this im am executing other methods based on the generated XML files

The SwingWorker code:

SwingWorker<Boolean, Void> ConvertersWorker = new SwingWorker<Boolean, Void>() {
    public Boolean doInBackground() {
        Boolean result = RunConverters();
        return result;
    }
    public void done() {
        try {
            finishedConverting = get();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        } catch (ExecutionException ex) {
            ex.printStackTrace();
        }
    }
 } ;

The second JPanel is not even displayed because the JFrame blocks. It blocks because of the while loop but I don't know how to implement it differently. And also the method done() from the SwingWorker is never executed. If it were executed then the finishedConverting variable would have been set to true and the while loop would have stopped. Can anyone help me to find a better solution?

有帮助吗?

解决方案

I know you solved this but that's happening because you are using just one thread, and it blocked because of the While, so you need to create a new thread to handle this

new Thread(){  
  public void run() { 
    //code here
  }
}.start();

and to refresh the content of a JPanel you can use

myJpanel.doLayout();

or

myJpanel.repaint();

其他提示

I removed the while loop and moved the code which was after the loop in another method which is executed in the done() method of the SwingWorker so now it works.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top