2012-02-16 67 views
1

我設計在NetBeans中的應用程序,如下面的截圖所示。的NetBeans和搖擺 - 動態添加的JPanel到的JDialog

enter image description here

當用戶點擊JFrame上一個JButton,一個JDialog彈出,詢問用戶輸入使用數字鍵盤的數值。我想JDialog動態添加2個JPanel。 JPanel 1將包含一個用於輸入的文本框。 JPanel 2將包含一個數字小鍵盤。我以這種方式設計它們,以便在需要時可以重複使用數字鍵盤。我面臨的問題是在彈出的JDialog上動態顯示這2個JPanel。 JDialog彈出空白。請看下面我的代碼。謝謝大家,我感謝您的幫助

這是的JDialog的示例代碼:

public class MyDialog extends javax.swing.JDialog { 

    public MyDialog(java.awt.Frame parent, boolean modal) { 
     super(parent, modal); 
     initComponents(); 

     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() {//Add JPanel 2 (Numeric Keypad) to JDialog 
       Container contentPane = getContentPane(); 
       NumericKeypadPanel nkp = new NumericKeypadPanel(); 
       nkp.setLayout(new java.awt.BorderLayout()); 
       contentPane.removeAll(); 
       contentPane.add(nkp); 
       contentPane.validate(); 
       contentPane.repaint(); 
      } 
     }); 
    } 

這是JPanel的2(數字鍵盤)的示例代碼:

public class NumericKeypadPanel extends javax.swing.JPanel { 

    /** Creates new form NumericKeypadPanel */ 
    public NumericKeypadPanel() { 
     initComponents();//Draws 10 number buttons 
    } 
} 

回答

3

basicall有兩種方法

1)通過在屏幕上保持JDialog大小(像素),它們的所有JCompoenets 或部分可以收縮

2添加新JComponent)通過調用pack()調整JDialog,然後JDialog將通過使用Standard LayoutManagers調整大小

both my a.m. rulles works(但0除外)

+0

謝謝mKorbel – jadrijan 2012-02-16 16:18:20

+0

很高興爲您效勞 – mKorbel 2012-02-16 16:30:30

1

NumericKeypadPanel的initComponents()函數是什麼?如果它實際上並沒有創建組件,那麼您不會在對話框中看到任何內容。我在NumericKeypadPanel的構造函數中添加了一行來更改此面板的背景顏色,事實上,它在對話框中顯示爲綠色面板。

public NumericKeypadPanel() { 
    //initComponents();//Draws 10 number buttons 
    setBackground(Color.green); 
} 
+0

的initComponents()函數是繪製數字按鈕。我意外地想出瞭解決方案。在NetBeans中,您可以簡單地將自定義的JPanel拖放到JDialog或JFrame上。解決方案非常簡單,我從未想過它。我需要更多地使用NetBeans來發現所有隱藏的功能。 – jadrijan 2012-02-16 16:17:15