2011-12-24 58 views
3

我得觀點:不能在飛行中添加的JPanel到JFrame中

  1. MainWindowView(擴展JFrame的)
  2. ScanOptimisationView(擴展JPanel)

所以,我在ComboBox MainWindowView類。我創建ActionListener並將其綁定到此組合框。此ActionListener的actionPerfomed()方法嘗試將ScanOptimisationView面板添加到主窗口框架。下面是代碼:

package ru.belaventcev.view; 

import java.awt.Container; 

public class MainWindowView extends JFrame{ 
    private int frmHeight = 525; 
    private int frmWidth = 650; 

    public Container frmContainer; 

    public static JButton btnCalc; 

    public static JComboBox cbMethods; 

    public MainWindowView(){ 
     setPreferredSize(new Dimension(frmWidth, frmHeight)); 
     setSize(frmWidth, frmHeight); 
     setLocationRelativeTo(null); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setResizable(false); 
     frmContainer = getContentPane(); 
     frmContainer.setLayout(new MigLayout("", "[grow,center]", "[::30px,grow,center][grow,center][::500px,grow,center][::25px,grow,center]")); 
     cbMethods = new JComboBox(); 
     cbMethods.setModel(new DefaultComboBoxModel(new JPanel[] {new ScanOptimisationView()})); 
     cbMethods.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       JPanel temp = (JPanel) cbMethods.getSelectedItem(); 
       frmContainer.add(temp, "cell 0 1,span"); 
      } 
     }); 

     /* 
     * If I uncomment this, panel is shown! 
     JPanel temp = (JPanel) cbMethods.getSelectedItem(); 
     frmContainer.add(temp, "cell 0 1"); 
     */ 

     frmContainer.add(cbMethods, "cell 0 0,growx"); 



     btnCalc = new JButton("Расчитать"); 
     frmContainer.add(btnCalc, "cell 0 3,alignx right"); 

    } 
} 

你能幫我明白 - 爲什麼面板不的actionPerformed()的代碼所示,但它顯示,當我用下面的代碼?

回答

5

在非工作情況下,在您的actionListener調用frmContainer.add()後,您需要致電frmContainer.validate()。從Container.add()的Javadocs:

「如果已將組件添加到已顯示的容器,則必須在該容器上調用驗證以顯示新組件。

當您響應點擊時,顯然您的容器已顯示。當您在構造函數中添加JPanel時,您的JFrame尚未顯示。

+0

它運作良好!謝謝!我需要更加關注文檔:) – dizpers 2011-12-24 07:40:28