Help needed for making a popup which automatically closes after a few seconds. JOptionpane messages usually needs an input to close, so is there any other way to handle auto-closing popup in java. Please help. Thanks in advance.
Asked
Active
Viewed 1.0k times
3
-
Possible [duplicate](http://stackoverflow.com/q/12448947/230513). – trashgod Aug 03 '14 at 13:37
1 Answers
7
If the option pane can be modeless, this might be one way to do it:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.Timer;
public class AutoCloseJOption {
private static final int TIME_VISIBLE = 3000;
public static void main(String[] args) {
final JFrame frame1 = new JFrame("My App");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setSize(100, 100);
frame1.setLocation(100, 100);
JButton button = new JButton("My Button");
frame1.getContentPane().add(button);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = new JOptionPane("Message", JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = pane.createDialog(null, "Title");
dialog.setModal(false);
dialog.setVisible(true);
new Timer(TIME_VISIBLE, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
}
}).start();
}
});
frame1.setVisible(true);
}
}
For this example, press the button and an option dialog will be visible for three seconds.

User0
- 564
- 3
- 10
-
The `TimerTask` callback is incorrectly synchronized; use `javax.swing.Timer`, as shown in either duplicate. – trashgod Aug 03 '14 at 13:40
-
2