javajframejlabelactionevent

How do I Get JFrame to Display JPanel Text Content Even When Called by Action Event?


I have a simple JFrame dialog, that should display "Please Wait" message while the main program completes other activities (which may take anywhere from 30 seconds to more than 10 minutes):

public JFrame waitDialog() {
         JFrame wait = new JFrame();
         wait.setTitle("My Dialog");
         wait.setAlwaysOnTop(true); 
         wait.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
         wait.setSize(300, 150);
         wait.setLocationRelativeTo(null);  
         wait.setLayout(new BorderLayout());
         String msg = "Plase Wait...";
         wait.add(new JLabel(msg), BorderLayout.CENTER);
         return wait;
    }

When I call it within the program flow, it works fine:

     ...
     JFrame wait = waitDialog();
     wait.setVisisble(true);
     for (int i=0;i<1000;i++){
         // Other activities
         System.out.println(i);
     }
     wait.setVisisble(false);
     ...

However, if I use execute this dialog via an ActionEvent (I click a "Do Other Activities" button on the main application JFrame), even though I use the EXACT SAME CODE to call waitDialog(), the dialog displays without any text. It displays an empty dialog without the "Please Wait..." message:

     public void actionPerformed(ActionEvent action){
     if (action.getSource==waitforit) {
         runWait(); 
     }

     Public void runWait() {
        JFrame wait = waitDialog();
     wait.setVisisble(true);
     for (int i=0;i<1000;i++){
         // Other activities
         System.out.println(i);
     }
     wait.setVisisble(false);
         }

I have reworked this extensively, and cannot understand why the JPanel text fails to display ONLY when I am calling the dialog through an ActionEvent.

What am I missing here?


Solution

  • You can't do it like that anyway. You have an incomplete picture of how Swing threading works. Have a look at the excellently documented SwingWorker and it will give you some ideas about how to accomplish what you want