java 如何用另一个 JPanel 替换 JPanel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14874613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:42:46  来源:igfitidea点击:

How to replace JPanel with another JPanel

javaswinglayoutjframejpanel

提问by Ardy Yonathan

I want to replace a Jpanel with another one in a JFrame I already search and try my code but nothing's happen this is my code :

我想用 JFrame 中的另一个 Jpanel 替换我已经搜索并尝试我的代码但没有任何反应这是我的代码:

public class Frame extends JFrame {

    private Container contain;
    private JPanel reChange,reChange2;
    private JButton reChangeButton;

    public Frame() {
        super("Change a panel");
        setSize(350, 350);
        setLayout(null);
        setLocationRelativeTo(null);
        setResizable(false);

        reChange = new JPanel(null);
        reChange.setBackground(Color.red);
        reChange.setSize(240, 225);
        reChange.setBounds(50, 50, 240, 225);
        add(reChange);

        reChangeButton = new JButton("Change It");
        reChangeButton.setBounds(20, 20, 100, 20);
        add(reChangeButton);

        reChangeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //System.out.println("in");
                contain = getContentPane();
                contain.removeAll();
                //System.out.println("in2");

                reChange2 = new JPanel(null);
                reChange2.setBackground(Color.white);
                reChange2.setSize(240, 225);
                reChange2.setBounds(50, 50, 240, 225);
                //System.out.println("in3");

                contain.add(reChange2);
                validate();
                //System.out.println("in4");
                setVisible(true);
                //System.out.println("in5");
            }
        });

    }

    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

can someone help me ? Thanks a lot

有人能帮我吗 ?非常感谢

回答by mKorbel

  1. don't to use AbsoluteLayout

  2. change validate();in actionPerformedto contain.validate();and follows with contain.repaint();

  3. rename class name (reserved Java word, or methods name) Frame(java.awt.Frame) to MyFrame(for example)

  4. use CardLayoutinstead of remove and then add a new JPanelon runtime

  1. 不要使用 AbsoluteLayout

  2. 改变validate();actionPerformedcontain.validate();与如下contain.repaint();

  3. 将类名(保留的 Java 字或方法名)Framejava.awt.Frame)重命名为MyFrame(例如)

  4. 使用CardLayout而不是删除然后JPanel在运行时添加一个新的

回答by Dan D.

You must call validate()and then repaint()on the containing panel after you do the remove and add operations.

执行删除和添加操作后,您必须在包含面板上调用validate()和 然后repaint()

contain.validate();
contain.repaint();

回答by Kusal Dissanayake

Try this, Following code will load the second jPanel (NewOrder) to first jPanel(jpMain)

试试这个,下面的代码会将第二个 jPanel (NewOrder) 加载到第一个 jPanel(jpMain)

NewOrder no = new NewOrder(); //This is the object of Second JPanel

// jpMain - This is the First JPanel
jpMain.setLayout(new java.awt.BorderLayout());
jpMain.removeAll();
jpMain.add(no);
jpMain.revalidate();

回答by Alya'a Gamal

you need to do like this :

你需要这样做:

     public void actionPerformed(ActionEvent e) {
        //System.out.println("in");
        contain = getContentPane();
        contain.removeAll();
        //System.out.println("in2");

        reChange2 = new JPanel(null);
        reChange2.setBackground(Color.white);
        reChange2.setSize(240, 225);
        reChange2.setBounds(50, 50, 240, 225);
        //System.out.println("in3");

        contain.add(reChange2);
        validate();
        repaint();
        //System.out.println("in4");
        setVisible(true);
        //System.out.println("in5");
    }
});

回答by Mikhail Vladimirov

Several issues with your code. Here is fixed version:

您的代码有几个问题。这是固定版本:

public class Frame extends JFrame {

    private Container contain;
    private JPanel reChange,reChange2;
    private JButton reChangeButton;

    public Frame() {
        super("Change a panel");
        setSize(350, 350);
        getContentPane().setLayout(null); // Changed here
        setLocationRelativeTo(null);
        setResizable(false);

        reChange = new JPanel(null);
        reChange.setBackground(Color.red);
        reChange.setSize(240, 225);
        reChange.setBounds(50, 50, 240, 225);
        getContentPane().add(reChange); // Changed here

        reChangeButton = new JButton("Change It");
        reChangeButton.setBounds(20, 20, 100, 20);
        getContentPane().add(reChangeButton); // Changed here

        reChangeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                contain = getContentPane();
                contain.removeAll();

                reChange2 = new JPanel(null);
                reChange2.setBackground(Color.white);
                reChange2.setSize(240, 225);
                reChange2.setBounds(50, 50, 240, 225);

                contain.add(reChange2);
                invalidate(); // Changed here
                repaint(); // Changed here
            }
        });
    }

    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

回答by user3785010

Assume you have a function, generatePanel() that returns a JPanel that you save in an instance variable of type JPanel:

假设您有一个函数 generatePanel() 返回一个 JPanel,您保存在 JPanel 类型的实例变量中:

private JPanel panelWithDynamicContent;

Assume you have already placed that JPanel into a container, perhaps at a specific index within that other container and want to preserve the order of the components within that container. Instead of destroying everything using removeAll(), I prefer a more precise approach that replaces only the component that needs to be replaced:

假设您已经将该 JPanel 放入一个容器中,可能位于该其他容器内的特定索引处,并希望保留该容器内组件的顺序。与其使用 removeAll() 销毁所有内容,我更喜欢一种更精确的方法,即仅替换需要替换的组件:

private void replacePanel(){
   Container parent = this.panelWithDynamicContent.getParent();
   int index = parent.getComponentZOrder(this.panelWithDynamicContent);
   // remove the old edition of the panel
   parent.remove(this.panelWithDynamicContent);
   // generate the replacement panel
   this.panelWithDynamicContent = generatePanel();
   // place the replacement panel in the same relative location as the one it is replacing
   parent.add(this.panelWithDynamicContent, index);

   // must call both of these, in the correct order
   parent.validate();
   parent.repaint();
}