Java.beginner
Java.beginner

Reputation: 891

Move JOptionPane's showConfirmDialog along with Java Application

I want to have warning showConfirmDialog window in front of the application even if GUI moves to different position, it works fine if I don't move the application and press 'Close ALT+X' button, but if I move the application to second screen the warning showConfirmDialog window stays at the old position, how to move the warning window along with GUI, please give me directions, thanks.

Close ALT+X button

        //close window button
    JButton btnCloseWindow = new JButton("Close ALT+X");
    btnCloseWindow.setMnemonic('x');
    btnCloseWindow.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFrame frame = new JFrame();

            int result = JOptionPane.showConfirmDialog(frame, "Are you sure you want to close the application?", "Please Confirm",JOptionPane.YES_NO_OPTION);
            //find the position of GUI and set the value
            //dialog.setLocation(10, 20);
            if (result == JOptionPane.YES_OPTION)
                System.exit(0);
        }
    });

SO far I tried to set position centre of the location of GUI to showConfirmDialog, but didn't work.

Upvotes: 1

Views: 770

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285415

The JOptionPane should position itself relative to its parent window. Since you're using a newly created and non-displayed JFrame as the dialog's parent window, the dialog only knows to center itself in your screen.

So the key here is not to use just any old JFrame as the parent window, but rather use your currently displayed JFrame or one of its displayed components as the parent component, the first parameter of your JOptionPane.showConfirmDialog method call.

So what if you make your JButton final and pass it into your method call?

// **** make this final
final JButton btnCloseWindow = new JButton("Close ALT+X"); // ***

// ....

btnCloseWindow.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

        // JFrame frame = new JFrame();  // **** get rid of this ****

        // ***** note change? We're using btnCloseWindow as first param.
        int result = JOptionPane.showConfirmDialog(btnCloseWindow , 
              "Are you sure you want to close the application?", 
              "Please Confirm",JOptionPane.YES_NO_OPTION);

        // ......

Upvotes: 5

Related Questions