java-CardLayout,通过ButtonClick在JPanels之间切换
作者:互联网
我想通过单击JPanels上的按钮在JPanels之间切换.
例如:
我有一个带有JButton simknop的JPanel sim和一个带有JButton helpknop的JPanel帮助
我想通过单击按钮在这两个JPanel之间切换.当我单击JButton simknop时,JPanel帮助应该
出现,当我单击JButton帮助时,应显示JPanel sim.
您可以在下面找到不同的类:
main.java
public class main extends JFrame
{
JPanel cards;
sim sim;
help help;
public main()
{
this.setSize(1024,768);
//this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Crazy Bombardement");
this.setLocation(800, 100);//standaard in de hoek van het scherm
cards = new JPanel();
cards.setLayout(new CardLayout());
sim = new sim();
help = new help();
cards.add(sim, "SIM");
cards.add(help, "HELP");
this.add(cards);
this.setVisible(true);
}
public static void main(String[] args)
{
new main();
}
sim.java
public class sim extends JPanel
{
JButton simknop;
public sim()
{
simknop = new JButton("simknop");
this.add(simknop);
this.setBackground(Color.black);
}
}
help.java
public class help extends JPanel
{
JButton helpknop;
public help()
{
helpknop = new JButton("helpknop");
this.add(helpknop);
this.setBackground(Color.red);
}
我想为此使用CardLayout,但无法弄清楚如何使其能够监听不同的ActionListeners.
任何帮助是极大的赞赏!
解决方法:
1)按钮不应位于CardLayout的每个面板上.无论卡面板上显示的是哪张卡,它们都必须位于始终可见的另一个外部面板上.
2)正确定位按钮后,您将向每个按钮添加一个ActionListener,其actionPerformed方法类似于(以SIM卡按钮为例):
CardLayout cl = (CardLayout) cards.getLayout();
cl.show(cards, "SIM");
编辑:从理论上讲,您可以在卡面板上直接放置按钮,但它是每个面板上的对面按钮(即SIM卡按钮在帮助面板上,反之亦然).
标签:cardlayout,swing,awt,layout-manager,java 来源: https://codeday.me/bug/20191031/1972670.html