我不知道是什么问题?我尝试使用 JButton 切换两个单独的类扩展 JPanel 和 cardLayout,但我不知道我是否使用了正确的代码......这是我的编码。
卡片布局菜单
public class CardLayoutMenu extends JFrame implements ActionListener{
CardLayout cardLayout = new CardLayout();
private JPanel p1 = new JPanel(cardLayout);
final String MAIN = "MAIN";
final String OPTION = "OPTION";
MainPanel mainPanel = new MainPanel();
OptionPanel optionPanel = new OptionPanel();
private Object object;
public CardLayoutMenu(Object object) {
this.object = object;
}
public CardLayoutMenu(){
setLayout(new BorderLayout());
setTitle("Card Layout Menu");
setSize(300,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
add(p1);
p1.add(mainPanel, MAIN);
p1.add(optionPanel, OPTION);
}
public void actionPerformed(ActionEvent e){
try{
cardLayout.show(p1, OPTION);
}catch(Exception ex){
System.out.println("" + ex);
}
}
}
这是我的主面板
public class MainPanel extends JPanel{
private JButton jbtOption = new JButton("Option");
public MainPanel() {
setLayout(new FlowLayout());
add(jbtOption);
jbtOption.addActionListener(new CardLayoutMenu(this));
}
}
然后我的OptionPanel,使用JButton jbtBack 回到MainPanel
public class OptionPanel extends JPanel{
private JButton jbtBack = new JButton("Back");
public OptionPanel() {
setLayout(new FlowLayout());
add(jbtBack);
}
}