2012-09-24 57 views
0

我在編程的Java桌面應用新的,所以我希望得到一些幫助...顯示一個JFrame或JDialog的(搖擺)

我添加了建設者框架的組成部分。

當我在我的主框架的按鈕點擊,我顯示的對話框是這樣的:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
      BehaviorDialog behavDialog = new BehaviorDialog(this, rootPaneCheckingEnabled); 
      behavDialog.setVisible(true); 
    } 

而且我BehaviorDialog類是這樣的:

public class BehaviorDialog extends javax.swing.JDialog { 

/** 
* Creates new form BehaviorDialog 
*/ 
public BehaviorDialog(java.awt.Frame parent, boolean modal) { 
    super(parent, modal); 
    initComponents(); 
    setTitle("Add behavior"); 
    setLocationRelativeTo(this); 
} 

/** 
* This method is called from within the constructor to initialize the form. 
* WARNING: Do NOT modify this code. The content of this method is always 
* regenerated by the Form Editor. 
*/ 
@SuppressWarnings("unchecked") 
// <editor-fold defaultstate="collapsed" desc="Generated Code">       
private void initComponents() { 
//.... 
}// </editor-fold>       

/** 
* @param args the command line arguments 
*/ 
public static void main(String args[]) { 
    /* Set the Nimbus look and feel */ 

    /* Create and display the dialog */ 
    java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
       BehaviorDialog dialog = new BehaviorDialog(new javax.swing.JFrame(), true); 
       dialog.addWindowListener(new java.awt.event.WindowAdapter() { 
        @Override 
        public void windowClosing(java.awt.event.WindowEvent e) { 
         System.exit(0); 
        } 
       }); 
       dialog.setVisible(true); 
      } 
     }); 
    } 
    // Variables declaration - do not modify      
    //... 
    // End of variables declaration     
} 

我的問題是:

  • 這是啓動幀/對話框的正確方法嗎? (它的工作原理,但我想,以確保它是否是最好的方式......)

  • 當我刪除在maininvokeLater(),似乎相同的方式工作。我要好好保存或我可以刪除它嗎?刪除它有什麼後果?

在此先感謝!

+0

另請參閱此替代方法[方法](http://stackoverflow.com/a/2561540/230513)。 – trashgod

回答

3

這是可能的方法之一。有些人喜歡爲每個對話框/窗口創建子類,所以該類正在管理自己的佈局和(經常)行爲。其他人更喜歡授權,即不要通過創建一種創建對話框及其佈局的工廠方法爲每個對話創建子類。我認爲這種方法更好,因爲它更靈活。您可以更輕鬆地將您的代碼分層。例如創建主面板的圖層,創建子面板的子圖層,將面板放入對話框的高層等等。將來,您可以替換處理對話框的圖層,並將相同的佈局放入JFrame或其他面板等。

關於invokeLater() - 它只是異步運行你的代碼。這對你的情況沒有意義。但對於需要時間的操作是有用的。例如,如果您想要執行按鈕上需要10秒鐘的操作,則可能需要異步運行此操作。否則,您的GUI將凍結10秒。

+0

謝謝您的回答!但是,你能指出我關於授權方法的正確方向嗎?如果你能告訴我一些例子/關於執行環節也將是巨大的......我已經搜查,但我沒有發現任何東西非常有用... – amp

3

我不認爲你的代碼有什麼問題。但是你一定要保持invokeLater,因爲它可以爲你處理線程。也就是說,它將這個事件排隊,直到其他AWT事件結束。這使您確信界面保持平穩運行。

,如果你想重用此JDialog的其他地方(和想要做小的修改喜歡的位置和大小),當然不過,我建議你移動和的setTitle(可能)setLocationRelativeTo方法來調用框架。

+0

但是''setVisible(true)'方法不會被執行兩次:1在我的主框架中,另一個在'invokeLater()'方法中?很抱歉,如果這個問題太明顯了...... – amp

+0

好,如果你決定將它移到了invokeLater(),那麼你只從構造函數中刪除它:) – Rorchackh