8

How can I specify the position of a JOptionPane. Can anyone make a class that extends JOptionPane.showInputDialog that also takes in an x,y position?

skaffman
  • 398,947
  • 96
  • 818
  • 769
CodeGuy
  • 28,427
  • 76
  • 200
  • 317

2 Answers2

6

You can use JOptionPane's setLocation(...) method. OR Instead of using JOptionPane you can extends a JDialog, and then specify it's location on the screen.

Here is one working code sample as adviced by @HovercraftFullOfEels , just this example will help you to get input from the user as you asked for :

import javax.swing.*;

public class OptionPaneLocation 
{   
    private void createAndDisplayGUI()
    {       
        JOptionPane optionPane = new JOptionPane("Its me"
                                    , JOptionPane.PLAIN_MESSAGE
                                    , JOptionPane.DEFAULT_OPTION
                                    , null, null, "Please ENTER your NAME here");
        optionPane.setWantsInput(true);             
        JDialog dialog = optionPane.createDialog(null, "TEST");
        dialog.setLocation(10, 20);
        dialog.setVisible(true);
        System.out.println(optionPane.getInputValue());
    }

    public static void main(String... args)
    {
        Runnable runnable = new Runnable()
        {
            public void run()
            {
                new OptionPaneLocation().createAndDisplayGUI();
            }
        };
        SwingUtilities.invokeLater(runnable);
    }
}
nIcE cOw
  • 24,468
  • 7
  • 50
  • 143
  • Doesn't the JDialog have nothing in it by default? – Perry Monschau Mar 21 '12 at 15:44
  • Yeah, true, but it can give functionality equivalent to `JOptionPane` or else you can use `setLocation(...)` method on the instance of `JOptionPane` as specified in my answer. – nIcE cOw Mar 21 '12 at 15:48
  • 1
    @Downvoter: Care to share your wisdom, on the topic, for the downvote. Will highly appreciate much, for learning somethingy new, if there is somethingy wrong, in my explanation :-) – nIcE cOw Nov 05 '14 at 01:52
5

A JOptionPane can be easily turned into a JDialog (check out the JOptionPane API and it will show you how with example). Then you can set the position of the created JDialog.

e.g., from the documentation:

 JOptionPane pane = new JOptionPane(arguments);
 pane.set.Xxxx(...); // Configure
 JDialog dialog = pane.createDialog(parentComponent, title);
 dialog.setLocation(....);  // added!
 dialog.setModal(....);  // added! Do you want it modal or not?
 // ....
 dialog.setVisible(true);
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373