change JPanel after clicking on a button

喜你入骨 提交于 2019-12-12 09:27:17

问题


I'm building simple GUI for my app. I have couple of JPanels. I want to display them depending on action that was performed by clicking on a JButton. How can I disable one JPanel and enable another one ?

Couple of details. I have a class with JFrame where I'm building starting gui. Where I have buttons and some text. Clicking on one of the buttons should change the view in this 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


回答1:


Simple as:

jframe.setContentPane(your_new_panel);
jframe.invalidate();
jframe.validate();



回答2:


  1. You may want to use CardLayout.
  2. Or you can simple remove the oldpanel and add new panel:

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



回答3:


First remove the jPanel and add the new jPanel. Then use validate to perform relayout.

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


来源:https://stackoverflow.com/questions/10984114/change-jpanel-after-clicking-on-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!