I need to add a progress bar in a JFrame but I want to update this bar without generating a new Thread (for example SwingWorker that update bar in background).
You should use Modal Dialog for blocking:
EDIT: progress visualization in EDT - that can also be done with your PropertyChangeEvent
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Test {
public Test() {
createAndShowGUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Test();
}
});
}
private void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setSize( 500, 500 );
frame.setLocationRelativeTo( null );
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout( new BorderLayout() );
frame.getContentPane().add(new JButton( openChooseGUI() ), BorderLayout.SOUTH);
frame.setVisible(true);
}
private Action openChooseGUI() {
return new AbstractAction("ChooseGUI") {
@Override
public void actionPerformed( ActionEvent e ) {
new ChooseGUI().setVisible( true );
}
};
}
public class ChooseGUI extends JFrame {
public ChooseGUI() {
setSize( 200, 200 );
setLocationRelativeTo( null );
setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
getContentPane().setLayout( new BorderLayout() );
getContentPane().add( new JLabel( "This is ChooseGUI" ), BorderLayout.CENTER );
init();
}
private void init() {
final JDialog progressDialog = new JDialog( this, true );
final JProgressBar progress = new JProgressBar( JProgressBar.HORIZONTAL );
progress.addChangeListener( new ChangeListener() {
@Override
public void stateChanged( ChangeEvent e ) {
// TODO Auto-generated method stub
int current = ((JProgressBar)e.getSource()).getValue();
if(current >= 100) {
progressDialog.dispose();
}
}
} );
progressDialog.setSize( 400, 100 );
progressDialog.setLocationRelativeTo( this );
progressDialog.getContentPane().setLayout( new BorderLayout() );
progressDialog.getContentPane().add( progress, BorderLayout.NORTH );
progressDialog.getContentPane().add( new JLabel( "This is Progress Dialog" ), BorderLayout.CENTER );
progressDialog.getContentPane().add( new JButton(new AbstractAction("click to progress") {
@Override
public void actionPerformed( ActionEvent e ) {
progress.setValue( progress.getValue()+25 );
}
}), BorderLayout.SOUTH );
progressDialog.setVisible( true );
}
}
}
You will end up with your EDT Thread blocked. You need to do your task in background, and you will update your progress bar from there.
By updating your progress bar I mean, setting its value. When you do that the GUI updates its view in EDT Thread automatically.