我尝试让CardLayout使用按钮更改面板内容(针对不同类中的内容),但由于某种原因,按钮(添加新项目)在点击时不会执行任何操作。< / p>
“添加新项目”按钮的事件侦听器正在尝试访问其他类(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 :(得分: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()是一个新方法,我返回包含所有卡片的JPanel(包括// proPanel面板)
pt = new ProTab();
tabPane.addTab("Projects", pt.getCardPanel());
tabPane.setBackgroundAt(2, (new Color(204, 255, 102)));