我的代码中有2个JPanel。第一个是Furutsu7,它是包含我的游戏的主要JPanel。第二个JPanel是Jbutton的开始。我想要完成的是在用户点击Jbutton之后,将出现Furutsu7 JPanel。
这是我创建按钮时的安装程序。
public void setup(){
JFrame f = new JFrame("Start ");
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
cards = new JPanel(new CardLayout());
JButton Card1Button = new JButton("Start");
card1.add(Card1Button);
JButton Card2Button = new JButton("Exit");
card2.add(Card2Button);
cards.add(card1, "C1");
cards.add(card2, "C2");
f.add(cards, BorderLayout.CENTER);
f.setTitle("Furutsu");
f.setSize(500, 300);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
我需要帮助的是,为了切换到Furutsu JPanel,我应该采取什么行动。
public void actionPerformed(ActionEvent e) {
}
答案 0 :(得分:5)
让您的CardLayout成为该类的一个字段,以便您可以在actionPerformed方法中更轻松地获取它。否则你需要致电(CardLayout) cards.getLayout()
,这是一件风险更高的事情。例如:
public class MyClass implements ActionListener {
private CardLayout cardLayout = new CardLayout();
private JPanel cards = new JPanel(cardLayout);
public void setup(){
JFrame f = new JFrame("Start ");
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
// cards = new JPanel(new CardLayout());
JButton Card1Button = new JButton("Start");
card1.add(Card1Button);
JButton Card2Button = new JButton("Exit");
card2.add(Card2Button);
cards.add(card1, "C1");
cards.add(card2, "C2");
f.add(cards, BorderLayout.CENTER);
f.setTitle("Furutsu");
f.setSize(500, 300);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
然后你可以直接引用它:
@Override
public void actionPerformed(ActionEvent e) {
// now you can call methods on your cardLayout variable:
cardLayout.show(...); // I'll leave it to you to figure out what to put in here
}
有关CardLayout的更多信息,请查看其tutorial
请注意,如果您只想按正向或反向顺序交换组件,请查看CardLayout的其他方法,例如next(cards)
和previous(cards)