I am trying to make a program that displays 3 MessageDialog
boxes at a time. I thought that if you put JOPtionPane.showMessageDialog
in an actionListner
class for a swing timer
, it would show a new MessageDialog
box every second.
So here is the code that I came up with:
package pracatice;
import java.awt.event.*;
import javax.swing.*;
public class practice extends JFrame
{
public static int num = 0;
public static TimerClass tc = new TimerClass();
public static Timer timer = new Timer(1000, tc);
public JPanel panel = new JPanel();
public JButton btn = new JButton("press");
public practice()
{
setSize(100,100);
setTitle("Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPanel();
setVisible(true);
}
public void setPanel()
{
btn.addActionListener(new listener());
panel.add(btn);
add(panel);
}
public class listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
num = 0;
System.out.println("starting timer");
timer.start();
}
}
public static class TimerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Adding 1 to num");
num++;
JOptionPane.showMessageDialog(null,"Test");
if(num == 3)
{
System.out.println("stopping the timer");
timer.stop();
}
}
}
public static void main(String[] args)
{
practice p = new practice();
System.out.println("created an instance of practice");
}
}
It works, but not the way I want it to. Instead of showing a new box every second it shows a new one 1 second after you press ok on the previous one.
So when I press "press" it waits 1 second and spawns the box. When I press "ok", it waits 1 second and spawns another one and so on. Any idea how to make the 3 boxes spawn 1 after another?