Question

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!

Was it helpful?

Solution

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();

OTHER TIPS

The JOptionPane will use the given parentComponent (first method parameter) to determine where to center the dialog (for example in javax.swing.JOptionPane.showMessageDialog(Component, Object))

You could try to pass in a fake component which positions the dialog to another location, for example like this:

    JFrame frame = new JFrame("Test");
    frame.setLocation(100, 100);
    frame.setSize(500, 500);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    // 'Invisible' fake component for positioning
    JWindow c = new JWindow();
    c.setSize(0, 0);
    c.setVisible(true);
    Point location = frame.getLocation();
    location.translate(200, 100);
    c.setLocation(location);

    JOptionPane.showInputDialog(c,"Foo");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top