0

I am trying to display a real-time counting in a simple java gui, I have used optionPane but there is a built-in button. So every time to display the next number, the user will have to press the button. Is there a way to let the numbers run by itself in a simple gui?

example:

for(int i = 0; i < 100; i++)
{
  JOptionPane.showMessageDialog(null, i);
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Look into [Swing Timers](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) and [SwingWorker](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html). – mre Mar 02 '14 at 02:04
  • Have a look at [this](http://stackoverflow.com/a/21619240/2587435) – Paul Samsotha Mar 02 '14 at 02:19

2 Answers2

1

Using a javax.swing.Timer is your best bet. You can run the example below. You can learn more at How to use Swing Timers

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class TimerDemo {

    static int count = 0;

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                final JLabel time = new JLabel(String.valueOf(count));

                Timer timer = new Timer(1000, new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        if (count >= 100) {
                            ((Timer) e.getSource()).stop();
                        } else {
                            count++;
                            time.setText(String.valueOf(count));
                        }
                    }
                });
                timer.start();
                JOptionPane.showMessageDialog(null, time);
            }
        });
    }
}

  • You can see a clock example here
  • You can Ssee more Timer examples here and here and here and here.
Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
0

Its not 1 dialog witch the user clicks OK, You popped up 100 dialogs,

java-love
  • 516
  • 1
  • 8
  • 23