2014-11-05 36 views
0

我想讓CardLayout使用按鈕更改面板(用於不同類中的內容)的內容,但由於某種原因按鈕(添加新項目)單擊時不會執行任何操作。我無法讓我的CardLayout使用按鈕切換卡片

事件偵聽器添加新項目按鈕,試圖達到一個不同的類(NewProject類)

... 
//CardLayout variables 
private JPanel cardPanel; 
private static final String CARD_PROJECTTAB = "Card Project Tab"; 
private static final String CARD_NEWPROJECT = "Card Add Project"; 
private NewProject newProject; 
//private TabPanel tp = new TabPanel(); 

// 

public ProTab(){ 

//Create cardPanel the panel that holds all the cards. 
cardPanel = new JPanel(); 
cardPanel.setLayout(new CardLayout(0,3));  

//Creating the proPanel that holds all other panels (below cardPanel) 
proPanel = new JPanel(); 
proPanel.setBackground(new Color(204, 255, 102)); 


/* 
    ========================== 
    CardLayout Class Instances 
    ========================== 
*/ 

cardPanel.add(proPanel, CARD_PROJECTTAB); 
newProject = new NewProject(); 
cardPanel.add(newProject, CARD_NEWPROJECT); 

//Creating the contentPane that holds all GUI components and 
//uses vertical/horizontal sidebars as needed 
contentPane = new JPanel(); 
contentPane.setBackground(Color.WHITE); 

//Giving the contentPane the GridBagLayout 
contentPane.setLayout(new GridBagLayout()); 
GridBagConstraints g = new GridBagConstraints(); 
g.insets = new Insets(20,0,0,0); 

... 

//Project bottom buttons START 

bButtonsPanel = new JPanel(); 
bButtonsPanel.setBackground(Color.WHITE); 
bButtonsPanel.setBorder(BorderFactory.createMatteBorder(0,0,0,0, Color.gray)); 
bButtonsPanel.setLayout(new FlowLayout()); 
    g.anchor = GridBagConstraints.PAGE_END; 
    g.gridx = 0; 
    g.gridy = 2; 
    contentPane.add(bButtonsPanel, g); 

viewProjectButton = new JButton("View Selected Project"); 
addProjectButton = new JButton ("Add a New Project"); 

bButtonsPanel.add(viewProjectButton); 
bButtonsPanel.add(addProjectButton); 

addProjectButton.addActionListener(new buttonListener()); 

//Project bottom buttons END 

} 

//Project bottom buttons ActionListeners 
private class buttonListener implements ActionListener{ 
    public void actionPerformed(ActionEvent ae){ 
     if (ae.getSource() == addProjectButton){ 
     CardLayout cl = (CardLayout) cardPanel.getLayout(); 
     cl.show(cardPanel, CARD_NEWPROJECT); 
     } 
    } 
} 

回答

0

我想通了。我的錯誤不在於實現CardLayout,但是我無法正確地從另一個c中調用包含CardLayout的JPanel。// getProTab()是一種返回帶有Project Tab元素的JPanel的方法。

pt = new ProTab(); 
    tabPane.addTab("Projects", pt.getProTab()); 
    tabPane.setBackgroundAt(2, (new Color(204, 255, 102))); 

後// getCardPanel()是我提出來返回包含所有卡(包括//的proPanel面板)JPanel中的新方法

pt = new ProTab(); 
    tabPane.addTab("Projects", pt.getCardPanel()); 
    tabPane.setBackgroundAt(2, (new Color(204, 255, 102)));