Java Swing How to - Use Timer to update UI with JOptionPane








Question

We would like to know how to use Timer to update UI with JOptionPane.

Answer

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//from   w w w .jav  a  2  s .c o  m
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Timer;

public class Main {
  public static void main( String[] args ) {
    JFrame f = new JFrame();

    JTextArea textArea = new JTextArea(  );
    f.add( new JScrollPane( textArea ), BorderLayout.CENTER );

    Timer timer = new Timer( 1000, new ActionListener() {
      @Override
      public void actionPerformed( ActionEvent e ) {
        textArea.append( "bla" );
      }
    } );
    timer.setRepeats( true );
    timer.start();
    JButton button = new JButton( "Click me" );
    button.addActionListener( e->{
        System.out.println("Before option pane");
        JOptionPane.showMessageDialog( f, "A message dialog" );
        System.out.println("After option pane");
    } );
    f.add( button, BorderLayout.SOUTH );
    f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    f.pack();
    f.setVisible( true );
  }
}