Can a progress bar be used in a class outside main?

后端 未结 3 744
孤独总比滥情好
孤独总比滥情好 2020-11-21 06:47

Right now, my main just calls a gui with 10 rows. Based on how many of those rows have text, 1 of 9 classes is called (two rows must have text). The called class performs

3条回答
  •  一生所求
    2020-11-21 07:30

    I think you premonition is right, you need to adhere to Swing threading rules.

    So what to do?

    First, I am not sure how your app is designed exactly. You say that you have a main frame with a bunch of rows, and potentially each could potentially call one of 9 classes, and they all look like the one above. It seems that these classes will generate their own JFrame. I guess that this new frame is solely used for the progress bar. I will assume that this is the design and will suggest accordingly.

    I suggest that you perform a couple actions in instances of Runnable, and you drop those Runnable instances into SwingUtilities.invokeLater to have them run on the EDT. At the same time, I would take the time to reorganize your code for ease if reading.

    1. move the creation of your GUI bits into a method:
    public void createComponents () {
          SwingUtilities.invokeLater(new Runnable() {
            public void run() {
              //Create all components
              progressFrame = new JFrame("Calculation Progress");
              progressFrame.setSize(300, 100);
              pane = progressFrame.getContentPane();
              pane.setLayout(null);
              progressFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              progressBar = new JProgressBar(0, iterations);
              //Add components to pane
              pane.add(progressBar);
    
              //Position controls (X, Y, width, height)
              progressBar.setBounds(10, 10, 280, 20);
    
              //Make frame visible
              progressFrame.setResizable(false); //No resize
              progressFrame.setVisible(true);
           }
          });
    
        }
    
    1. Then I would methodize the two GUI actions that you have in your calc:
         private void updateProgressBar(final int i) {
               SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                       progressBar.setValue(i);
                       //no need for the following
                       //progressBar.repaint(); 
    
                    }
               });
        }
    
        private void killDialog() {
               SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        progressFrame.setVisible(false);
                    }
                });
        } 
    
    1. Finally, replace where the code contained in these new methods with calls to the methods.

提交回复
热议问题