Closing a Joptionpane Programmatically

Closing A JOptionPane Programmatically

Technically, you can loop through all windows of the application, check is they are of type JDialog and have a child of type JOptionPane, and dispose the dialog if so:

Action showOptionPane = new AbstractAction("show me pane!") {

@Override
public void actionPerformed(ActionEvent e) {
createCloseTimer(3).start();
JOptionPane.showMessageDialog((Component) e.getSource(), "nothing to do!");
}

private Timer createCloseTimer(int seconds) {
ActionListener close = new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
Window[] windows = Window.getWindows();
for (Window window : windows) {
if (window instanceof JDialog) {
JDialog dialog = (JDialog) window;
if (dialog.getContentPane().getComponentCount() == 1
&& dialog.getContentPane().getComponent(0) instanceof JOptionPane){
dialog.dispose();
}
}
}

}

};
Timer t = new Timer(seconds * 1000, close);
t.setRepeats(false);
return t;
}
};

How to close message dialog programmatically?

You could always get a reference to the JOptionPane by getting the WindowAncestor of any component it's holding, and then call dispose() or setVisible(false) on the Window returned. The Window can be obtained by using SwingUtilities.getWindowAncestor(component)

For example:

import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class CloseOptionPane {

@SuppressWarnings("serial")
private static void createAndShowGui() {
final JLabel label = new JLabel();
int timerDelay = 1000;
new Timer(timerDelay , new ActionListener() {
int timeLeft = 5;

@Override
public void actionPerformed(ActionEvent e) {
if (timeLeft > 0) {
label.setText("Closing in " + timeLeft + " seconds");
timeLeft--;
} else {
((Timer)e.getSource()).stop();
Window win = SwingUtilities.getWindowAncestor(label);
win.setVisible(false);
}
}
}){{setInitialDelay(0);}}.start();

JOptionPane.showMessageDialog(null, label);

}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Closing a dialog created by JOptionPane.showOptionDialog()

final JButton btn = new JButton("Close");

btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Window w = SwingUtilities.getWindowAncestor(btn);

if (w != null) {
w.setVisible(false);
}
}
});

How to close JOptionPane directly by closing JFrame?

Dialog modality is the key

You can't do this with a normal JOptionPane or with any modal dialog as the modality prevents the user from interacting with other components of the GUI while the dialog is displayed. You can only get this to work if you create a non-modal dialog, meaning that the JOptionPane must be created not with the JOptionPane static factory methods, but rather in a non-traditional way, using a JOptionPane constructor -- check the JOptionPane API for how to do this.

For example:

import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.event.ActionEvent;

import javax.swing.*;

public class NonModalJOptionPane {

private static void createAndShowGui() {
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(400, 300));

final JFrame frame = new JFrame("NonModalJOptionPane");

panel.add(new JButton(new AbstractAction("Push Me") {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane optionPane = new JOptionPane("My Message", JOptionPane.PLAIN_MESSAGE);
JDialog dialog = optionPane.createDialog(frame, "My Option");
dialog.setModalityType(ModalityType.MODELESS); // **** key ***
dialog.setVisible(true);
}
}));

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

The key to this code is here:

// create the JOptionPane using one of its constructors
JOptionPane optionPane = new JOptionPane("My Message", JOptionPane.PLAIN_MESSAGE);

// create a JDialog from it, tying it to the parent JFrame, here called "frame"
JDialog dialog = optionPane.createDialog(frame, "My Option");

// setting the modality type so that it is **not** modal
dialog.setModalityType(ModalityType.MODELESS); // **** key ***

// and then displaying it
dialog.setVisible(true);

Where I create a JOptionPane via its constructor, not via a static method, I create a JDialog and set it to be MODELESS, and then display it.


Another viable option is to create your own JDialog, making sure that you set it to being non-modal as well.

For example, you could add the following code to the code above:

panel.add(new JButton(new AbstractAction("Push Me 2 -- Using Dialog") {
@Override
public void actionPerformed(ActionEvent e) {
// button that when pressed, closes the JDialog that holds it
// similar to a JOptionPane's OK button
JButton disposeWinBtn = new JButton(new DisposeWindowAction("OK", KeyEvent.VK_O));

// create a bunch of JPanels, add components to them, ...
JPanel bottomPanel = new JPanel();
bottomPanel.add(disposeWinBtn);

JLabel msgLabel = new JLabel("My Message");
JPanel msgPanel = new JPanel();
msgPanel.add(msgLabel);

JPanel panel = new JPanel(new BorderLayout());
panel.add(msgPanel, BorderLayout.CENTER);
panel.add(bottomPanel, BorderLayout.PAGE_END);

// create a JDialog whose parent component is the main JFrame
// and make sure that it is *****non-modal ***** <===== this is KEY *****
JDialog dialog = new JDialog(frame, "Dialog", ModalityType.MODELESS);
dialog.add(panel); // add the JPanel, panel, created above, with components
dialog.pack(); // have layout managers do their thing
dialog.setLocationRelativeTo(frame); // center it over the main JFrame
dialog.setVisible(true); // and display it
}
}));

just under where the first button is added. You'll also need the DisposeWindowAction class, that allows the button to close and dispose of the window that is displaying it (here a JDialog window):

import java.awt.Component;
import java.awt.Window;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class DisposeWindowAction extends AbstractAction {
public DisposeWindowAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}

@Override
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
if (component == null) {
return;
}
Window win = SwingUtilities.getWindowAncestor(component);
if (win == null) {
return;
}
win.dispose();
}
}

Closing a runnable JOptionPane

Yes, the trick would be to get the Timer started before you call setVisible...

public class AutoClose02 {

public static void main(String[] args) {
new AutoClose02();
}

private Timer timer;
private JLabel label;
private JFrame frame;

public AutoClose02() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}

JOptionPane op = new JOptionPane("Breaktime", JOptionPane.WARNING_MESSAGE);
final JDialog dialog = op.createDialog("Break");
dialog.setAlwaysOnTop(true);
dialog.setModal(true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

// Wait for 1 minute...
timer = new Timer(60 * 1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
timer.setRepeats(false);
// You could use a WindowListener to start this
timer.start();

dialog.setVisible(true);
}
}
);
}

}

How to close a JOptionPane message box when pressing the x button?

It is just simple.

//First of all put the options dialog code like this.
int n = JOptionPane.showOptionDialog(this, "?", "Check", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,null,null,null);
//Now grab the value of n into switch case like this.
switch(n)
{
case 0:
//Yes
break;
case 1:
//No
break;
case 2:
//Cancel
break;
case -1:
//User pressed 'X' button on the options dialog.If you want to exit app here.
System.exit(0);
break;
}

Here is a tip.

If you want to check the return value of any message dialog just get the return value and print it on the console or just show another message box with the return value in it.So you can understand easily,what happens when user press what button in the message dialog.

Hope this will solve your problem.



Related Topics



Leave a reply



Submit