1 java swing jbutton layout-manager cardlayout
我的代码中有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);
}
Run Code Online (Sandbox Code Playgroud)
我需要帮助的是我应该为了切换到Furutsu JPanel而执行的操作.
public void actionPerformed(ActionEvent e) {
}
Run Code Online (Sandbox Code Playgroud)
使您的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);
}
Run Code Online (Sandbox Code Playgroud)
然后你可以直接引用它:
@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
}
Run Code Online (Sandbox Code Playgroud)
有关CardLayout的更多信息,请查看其教程
请注意,如果您只想以向前或向后的顺序交换组件,请查看CardLayout的其他方法,例如next(cards)和previous(cards)