2014-05-01 91 views
0

我在添加另一個JPanel到我的框架時,我使用組合框的問題。 我想根據組合框中的選擇更改中央面板。 我爲所有選擇製作了不同的面板,但沒有添加到我的主面板中。 我添加了代碼。廣告選擇的面板丟失JCombobox

謝謝:)

import AllClasses.FlightCompany; 
{ 
public class WorkerDialog extends JFrame { 
    private JPanel Worker; 
    private String[] LabelNames = { "Worker Type:", " Worker Name:" }; 
    String [] str = { "Office", "Host", 
    "Pilot" }; 
    JComboBox<String> ChooseBox = new JComboBox<>(str); 
    public JPanel MainPanel; 
    private JPanel [] p= new JPanel[3]; 

    public WorkerDialog(FlightCompany f) { 
     super("Worker Dialog"); 

     p[0] = new Office_Gui(); 
     p[1] = new Host_Gui(); 
     p[2] = new Pilot_Gui(); 
     Worker = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5)); 
     JLabel LabelName = new JLabel(LabelNames[0]); 
     JLabel LabelName2 = new JLabel(LabelNames[1]); 
     JTextField fieldBox = new JTextField(); 
     LabelName.setSize(40, 25); 
     ChooseBox.setPreferredSize(new Dimension(180, 22)); 
     Worker.add(LabelName); 
     Worker.add(ChooseBox); 
     Worker.add(LabelName2); 
     fieldBox.setPreferredSize(new Dimension(180, 22)); 
     Worker.add(fieldBox); 
     JPanel AddPanel = new JPanel(new GridLayout(2, 1, 1, 1)); 
     AddPanel.add(new JButton("Add")); 
     AddPanel.add(new JButton("TakeOff")); 
     MainPanel = new JPanel(new BorderLayout(3, 3)); 
     AddPanel.setPreferredSize(new Dimension(0, 110)); 
     ChooseBox.addItemListener(new ItemListener() { 



      @Override 
      public void itemStateChanged(ItemEvent e) { 
       // TODO Auto-generated method stub 
       //String str = e.getActionCommand(); 
       String jb = (String) ChooseBox.getSelectedItem(); 
       if (jb.equals("Office")){ 

        MainPanel.add(p[0],BorderLayout.CENTER); 
        System.out.println("Office");} 
      } 
     }); 








     MainPanel.add(Worker, BorderLayout.NORTH); 
     MainPanel.add(AddPanel, BorderLayout.SOUTH); 
     add(MainPanel); 
     //pack(); 
     setSize(560, 300); 
     setAlwaysOnTop(true); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     setLocationRelativeTo(null); 
     setResizable(false); 
     setVisible(true); 

回答

1

你想要做的是使用CardLayoutmainPanel,這將讓您輕鬆面板之間切換。然後將所有面板添加到mainPanel,指定面板的名稱。該名稱將在組合框中顯示。當您想要顯示某個面板時,只需撥打cardLayout.show(mainPanel, "nameOfPanel")

要了解有關Cardlayout的更多信息,請參閱How to Use CardLayout。您還可以看到一個簡單示例here

另一方面:使用Java命名約定。變量以小寫字母開頭,使用駱駝套。即:

  • ChooseBoxchooseBox
  • MainPanelmainPanel