简体   繁体   English

在JApplet中切换JPanel

[英]Switching JPanel within JApplet

here is the question. 这是问题。 I have a JApplet, and inside the applet I have two JPanels, panel1 and panel2. 我有一个JApplet,在小程序内有两个JPanels,panel1和panel2。 Each panel has a label shown "panel1" or "panel2", and each panel has a button called "switch". 每个面板都有一个显示为“ panel1”或“ panel2”的标签,每个面板都有一个名为“ switch”的按钮。 When I run the applet, I only want panel1 to be visible. 运行小程序时,我只希望显示panel1。 And when I click the switch button, I wanna panel1 to be invisible (or disappear) and panel2 to be visible. 当我单击切换按钮时,我希望panel1不可见(或消失),而panel2不可见。 I will also want to click the switch button in panel2 to switch back to panel1. 我还将要单击panel2中的切换按钮以切换回panel1。 Can anyone help me with this? 谁能帮我这个?

public class MyApplet extends JApplet
{
    private Panel1 panel1;
    private Panel2 panel2;

    public void init()
    {
        setLayout(new FlowLayout());

        panel1 = new Panel1();
        panel2 = new Panel2();

        add(panel1);
        //add(panel2);
    }
}

public class Panel1 extends JPanel
{
    private JLabel label;
    private JButton button;

    public Panel1()
    {
        setLayout(new FlowLayout());

        label = new JLabel("Panel1");
        button = new JButton("Switch1");

        add(label);
        add(button);
    }
}

public class Panel2 extends JPanel
{
    private JLabel label;
    private JButton button;

    public Panel2()
    {
        setLayout(new FlowLayout());

        label = new JLabel("Panel2");
        button = new JButton("Switch2");

        add(label);
        add(button);
    }
}

Add a "content" to the applet, where you want to switch panels in and out off. 在小程序中添加一个“内容”,您要在其中切换面板。

Set this panels layout manager to CardLayout 将此面板布局管理器设置为CardLayout

Add your other panels to the "content" pane 将其他面板添加到“内容”窗格中

content.add(aPanel, "PanelA");
content.add(bPanel, "PanelB");

Use the CardLayout API to switch the panels... 使用CardLayout API切换面板...

cardLayout.show(content, "PanelB");

Have a read through How to Use CardLayout for more details 阅读有关如何使用CardLayout的详细信息

Add them both to the applet, and setVisible(false) on one of them. 将它们都添加到applet中,并在其中一个上设置setVisible(false)。

Add listeners for the buttons. 为按钮添加侦听器。

The listeners will toggle the setVisible of the appropriate panel. 侦听器将切换适当面板的setVisible。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM