2014-12-02 52 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

相關問題