简体   繁体   English

单击按钮后更改JPanel

[英]change JPanel after clicking on a button

I'm building simple GUI for my app. 我正在为我的应用程序构建简单的GUI。 I have couple of JPanels. 我有几个JPanels。 I want to display them depending on action that was performed by clicking on a JButton. 我想根据单击JButton所执行的操作来显示它们。 How can I disable one JPanel and enable another one ? 如何禁用一个JPanel并启用另一个JPanel?

Couple of details. 几个细节。 I have a class with JFrame where I'm building starting gui. 我有一个JFrame课,我正在这里开始gui的构建。 Where I have buttons and some text. 我有按钮和一些文字的地方。 Clicking on one of the buttons should change the view in this JFrame 单击其中一个按钮应更改此JFrame中的视图

my button definition 我的按钮定义

    JButton btnStart = new JButton("Start");
    btnStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        }
    });
    btnStart.setBounds(10, 11, 110, 23);
    contentPane.add(btnStart);

// edit //编辑

I've found the problem. 我发现了问题。 buttons were in static method 按钮是静态方法

Simple as: 简单为:

jframe.setContentPane(your_new_panel);
jframe.invalidate();
jframe.validate();
  1. You may want to use CardLayout . 您可能要使用CardLayout
  2. Or you can simple remove the oldpanel and add new panel: 或者,您可以简单地删除旧面板并添加新面板:

contentPane.remove(oldPanel);
contentPane.add(newPanel);

First remove the jPanel and add the new jPanel. 首先删除jPanel并添加新的jPanel。 Then use validate to perform relayout. 然后使用验证执行中继。

    jFrame.remove(jPanelOld);
    jFrame.add(jPanelNew);
    jFrame.validate();

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

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