Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting hold of a reference to the object created by JOptionPane static methods

I wonder if it is possible to get hold of a reference to the (JDialog?) object created by one of those static methods of JOptionPane (e.g. showMessageDialog)? I intend to modify the position where the dialog appears on the screen. More specifically, I want the dialog to appear at the top-left corner of the main app window, instead of the centre of the window by default. So having a reference to the object would enable me to use setLocation to achieve the desired effect...

Any suggestion would be appreciated! Thanks!

like image 502
skyork Avatar asked Dec 28 '10 00:12

skyork


People also ask

What is the return type from invoking JOptionPane showInputDialog () method?

JOptionPane. showInputDialog() will return the string the user has entered if the user hits ok, and returns null otherwise.

What are the 4 JOptionPane dialog boxes?

You can use a custom icon, no icon at all, or any one of four standard JOptionPane icons (question, information, warning, and error).


1 Answers

The static showXXXDialog() methods are just for convenience. If you look at the source code for JOptionPane, you'll find that in actuality, a JOptionPane object is created based on the options you specify and then JOptionPane.createDialog(...) is called. One method to show your message dialog at a different position is:

JOptionPane pane = new JOptionPane("Message", JOptionPane.WARNING_MESSAGE,
        JOptionPane.DEFAULT_OPTION);
JDialog dialog = pane.createDialog("TITLE");
dialog.setLocation(0, 0);
dialog.setVisible(true);

// dialog box shown here

dialog.dispose();
Object selection = pane.getValue();

With a combination of parameters to the JOptionPane constructor, and JOptionPane set methods, you can do anything you would have done with the static methods, plus you have access to the JDialog object itself.

EDITED: (to add example of input dialog for OP)

JOptionPane pane = new JOptionPane("Message", JOptionPane.QUESTION_MESSAGE,
        JOptionPane.OK_CANCEL_OPTION, null, null, null);
pane.setWantsInput(true);
JDialog dialog = pane.createDialog(null, "Title");
dialog.setLocation(0, 0);
dialog.setVisible(true);

String str = (String) pane.getInputValue();
like image 52
robert_x44 Avatar answered Oct 05 '22 23:10

robert_x44