如何交换 2 个 jPanel 位置?

问题描述

所以我创建了一个新的 jFrame,其中有 2 个 jPanel - jPanel1 和 jPanel2。

我需要这两个 jPanel 来交换位置,第一个到第二个的位置,第二个到第一个的位置(所有内容都将在 jPanel 中)。

最好的方法是什么?

enter image description here

解决方法

这取决于您在父面板中使用的布局,但基本上,您必须从公共父面板中删除两个组件(内容 1 和内容 2)并在另一个位置再次添加它们。

我做了一个简单的例子,它有一个(水平)流布局和两个面板,上面只有一个标签——但它也适用于更复杂的面板。

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

public class TestFrame extends JFrame  {

    public static void main(String[] args) throws InterruptedException {
        TestFrame f = new TestFrame();

        f.getContentPane().setLayout(new FlowLayout());

        JPanel pnl1 = new JPanel();
        pnl1.add(new JLabel("My first label"));

        JPanel pnl2 = new JPanel();
        pnl2.add(new JLabel("My second label"));

        f.getContentPane().add(pnl1);
        f.getContentPane().add(pnl2);

        f.setSize(400,400);
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.setVisible(true);

        // wait 2 seconds and switch panels
        System.out.println("before sleep");
        Thread.sleep(2000);
        System.out.println("after sleep");

        // remove the old content - could be more "precise" in real world - not just remove all components
        f.getContentPane().removeAll();

        // add the components in different order (in flow layout)
        f.getContentPane().add(pnl2);
        f.getContentPane().add(pnl1);

        // render again
        f.revalidate();
    }
}
,
import javax.swing.*;
import java.awt.GridLayout;    

public class Class {
    static JFrame frame;
    static JPanel panel1 = new JPanel();
    static JPanel panel2 = new JPanel();
    public static void main(String[] args) {
        panel1.add(new JLabel("Panel 1"));
        panel2.add(new JLabel("Panel 2"));

        frame = new JFrame();
        frame.getContentPane().setLayout(new GridLayout(1,2));
        frame.setVisible(true);
        frame.setSize(500,500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        frame.getContentPane().add(panel1);
        frame.getContentPane().add(panel2);

        new Timer(2000,e -> {
            frame.getContentPane().removeAll();
            frame.getContentPane().add(panel2);
            frame.getContentPane().add(panel1);
            frame.getContentPane().revalidate();
        }).start();
    }
}