在 Java 帧中的 JPanel 表单之间切换

Switching between JPanel Forms in Java Frame

我正在为 JPanel 苦苦挣扎。我想要 1 个框架,我在其中放置 1 个 MainJPanel,然后添加一些 JPanel Forms,将其设置为我的 MainJPanel 的源。 然后在 JPanel Forms 之间切换

我的 Main.java 框架中有这个:

public class Main extends javax.swing.JFrame {
    PanelForm1 p1 = new PanelForm1();
    PanelForm2 p2 = new PanelForm2();
    GridBagLayout layout = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();

    public Main() {
        initComponents();
        MainJPanel.setLayout(layout);
        c.gridx = 0;
        c.gridy = 0;
        MainJPanel.add(p1,c);
        c.gridx = 0;
        c.gridy = 0;
        MainJPanel.add(p2,c);
        m.p1.setVisible(true);
        m.p2.setVisible(false);
    }
}

并且在 PanelForm1.java 我的 ButtonClick 试图显示 Panel2Form。

public class Panel1 extends javax.swing.JPanel {

    public Panel1() {
        initComponents();    
    }

    private void ButtonGoToPanel2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        Main m = new Main();
        m.p1.setVisible(false);
        m.p2.setVisible(true);
    }  
}

Panel2Form.java 可能是一样的。

我能做到的唯一方法是让按钮就在 Main.java 中,但我不想让按钮始终可见。

我知道,当我创建一个 Class 对象时 Main m = new Main(); 我是 p1p2 等的新副本,所以我没有改变任何东西。

有人可以帮忙吗?或者有另一种更好的方法来做到这一点? 我不想把所有东西都放在一个文件里,因为它不会很清楚,而且像 CardLayout 这样的每个方法都不会去,因为我不想总是有按钮来切换 JPanel Forms。

Then to switch between JPanel Forms

所以你应该使用 CardLayout。有关工作示例,请参阅 How to Use CardLayout 上的 Swing 教程部分。

The only way I can do it is to have buttons right in Main.java, but I don't want to have buttons, which are always visible

嗯,面板不会自行切换,因此您需要处理某种事件来启动面板交换:

  1. 用户点击菜单项
  2. 用户点击按钮
  3. 用户输入了一个击键
  4. 应用程序切换面板

然后将一个参数从子面板传递到主面板,指示要显示哪个面板。

I don't want to have everything in one file, because it won't be clear

没有必要将所有内容都放在一个文件中。子面板需要访问父面板。

一种方法是传递参数:

JPanel main = new JPanel();
JPanel child1 = new ChildPanel(main);
main.add(child1);
JPanel child2 = new ChildPanel(main);
main.add(child2);

and also every method like CardLayout won't go, because I don't want always to have buttons to switch JPanel Forms

是的,您可以使用 CardLayout。不,你不需要按钮。您只需要显示 "panel name" 即可。然后用 CardLayout 通知面板。