0

I´ve got a project and I want to change the value of the progressbar with a call from another class. How could I implement this?

    static class ButtonActionListener implements ActionListener {
    @Override public void actionPerformed( ActionEvent e ) {
      new Thread( new Runnable()
      {
        @Override public void run()
        {
          for ( int i = 1; i <= bar.getMaximum(); ++i )
          {
            final int j = i;

            SwingUtilities.invokeLater( new Runnable()
            {
              @Override public void run() {
                bar.setValue( j );
              }
            } );
          }
        }
      } ).start();
    }
  }
Gerwin
  • 1,572
  • 5
  • 23
  • 51
lofoxx
  • 1
  • 1

1 Answers1

0

You call bar.setValue(...) to change the progress.

However, beware that you can only do this safely from code that runs on the Swing event listener thread. Calling this method from another thread is liable to lead to obscure failures that only happen occasionally, are hard to test for, and hard to track down.

Using SwingUtilities.invokeLater(...) to make the change is the right approach. You can do this from any code that has access to the bar reference. For example, you could expose it via a getter.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216