Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java joptionpane which automatically closes after few seconds [duplicate]

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.

like image 539
sneha nambiar Avatar asked Aug 11 '26 14:08

sneha nambiar


1 Answers

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.

like image 199
User0 Avatar answered Aug 13 '26 04:08

User0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!