javaswingjprogressbar

Update progress bar with data comming from an inner class in Java


I have a primary class, with the swing components, that calls a secondary class that makes lots of stuff that I want to show a progress bar for. How can I do that without having to bring the whole code from the secondary to the primary class?

Here is the simplified code:

public class ProgressBar {

    public static void main(String[] args) {
        GUI gui = new GUI();
        gui.showGUI();
    }
}
import javax.swing.*;

public class GUI {
    private JFrame mainFrame;
    
    public void showGUI() {
        mainFrame = new JFrame();
        mainFrame.setSize(222, 222);
        mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
        Primary primary = new Primary();
        mainFrame.add(primary.getPanel());
        mainFrame.setVisible(true);
    }
}
import javax.swing.*;

public final class Primary {
    private JPanel primaryPanel;
    
    public Primary(){
        createPanel();
    }
    
    public void createPanel() {
         primaryPanel = new JPanel();
         primaryPanel.setSize(333, 333);
         
         JTextArea textArea = new JTextArea();
         Secondary secondary = new Secondary();
         textArea.setText(secondary.writeInfo(11));
         primaryPanel.add(textArea);
         
         JProgressBar progressBar = new JProgressBar();
         primaryPanel.add(progressBar);
         
         primaryPanel.setVisible(true);
    }
    
    public JPanel getPanel(){
        return primaryPanel;
    }
}
public class Secondary {
    private String info;
    public int progress;
    
    public Secondary(){
        info = "";
    }
    
    public String writeInfo(int n){
        for(int i=1; i<=n; i++) {
            info += " bla";
            progress = 100*i/n;
            //System.out.println(progress);
        }
        return info;
    }
}

Solution

  • You don't need to bring the whole code from Primary to Secondary class. You can just pass in the ProgressBar to the Secondary class in Constructor and update it from there according to your logic.

    Secondary secondary = new Secondary(progressBar);
    

    However, depending on the logic you are implementing in Secondary Class, this may be against Single Responsibility Principle. So instead, what you can also do is to implement the Observer Pattern and notify the Primary Class from your Secondary class every time the progress needs to be updated.