2014-12-02 56 views
1

即使GUI移动到不同位置,我也希望在应用程序前面有警告showConfirmDialog窗口,如果我不移动application并按下'关闭ALT + X'按钮,它会正常工作,但如果我将应用程序移动到第二个屏幕,警告showConfirmDialog窗口停留在旧位置,如何随GUI一起移动警告窗口,请给我指示,谢谢。将JOptionPane的showConfirmDialog与Java应用程序一起移动

关闭ALT + X键

 //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); 
     } 
    }); 

到目前为止,我试图设置的GUI showConfirmDialog的位置的位置中心,但没有奏效。

回答

5

JOptionPane应该相对于其父窗口定位自己。由于您使用的是新创建的和未显示的JFrame作为对话框的父窗口,因此该对话框只知道将它自己居中在屏幕中。

所以这里的关键是不要使用任何旧的JFrame作为父窗口,而是使用您的当前显示的JFrame或它的显示组件的父组件,您JOptionPane.showConfirmDialog方法的第一个参数之一呼叫。

那么如果你让你的JButton final并将它传递给你的方法调用呢?

// **** 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); 

     // ...... 
+0

Thanks @Hovercraft当我将btnCloseWindow更改为frmViperManufacturingRecord时,警告窗口即将到来。 'int result = JOptionPane.showConfirmDialog(frmViperManufacturingRecord,“你确定要关闭应用程序?”,“请确认”,JOptionPane.YES_NO_OPTION);'非常感谢你的时间和帮助 – 2014-12-02 13:22:53

相关问题