【发布时间】:2014-11-09 13:25:52
【问题描述】:
首先,我没有收到任何错误。所以这可能是一个逻辑错误。
我正在尝试切换到playMenu 面板,但是当我按下按钮(在mainMenu 类中)时,什么也没有发生。是的,方法switchCard 被调用,因为我用一个简单的println. 进行了检查
这是包含内容面板的 Frame 类。
我删除了不相关的变量。
//Panel Final Names
private final String MENU_ID = "menu";
private final String PLAY_ID = "play";
//Panels(Cards)
private MainMenu mainMenu;
private Play playMenu;
//JFrame
private JFrame frame = new JFrame("Battleships");
//Panel that will hold the card panel
private CardLayout cl = new CardLayout();
private JPanel contentPanel = new JPanel(cl);
//Constructors
public Frame(){}
public Frame(boolean x){
GUI();
}
public void GUI(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
/*
Passing Parameters to MainMenu class so
you can do operations like changing panels and
disposing the main JFrame from a different class
*/
mainMenu = new MainMenu(frame, contentPanel);
playMenu = new Play(frame, contentPanel);
//Adding menu panel as a card in contentPanel
contentPanel.add(mainMenu, MENU_ID);
contentPanel.add(playMenu, PLAY_ID);
//Adding contentPanel to JFrame
frame.add(contentPanel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Frame(true);
}
});
}
public void switchCard(){
contentPanel.setLayout(new CardLayout());
CardLayout cl = (CardLayout) contentPanel.getLayout();
cl.show(contentPanel, PLAY_ID);
}
这是我要切换到的 JPanel。我删除了 NetBeans 自动生成的代码。如果它以某种方式与这个问题相关,我会发布它。
public class Play extends javax.swing.JPanel {
/**
* Creates new form Play
*/
private JFrame parentFrame;
private JPanel contentPanel;
public Play(JFrame frameIn, JPanel panelIn) {
initComponents();
contentPanel = panelIn;
parentFrame = frameIn;
}
}
【问题讨论】:
标签: java swing user-interface layout-manager cardlayout