Java 更改GridLayout中两个组件的位置

Java 更改GridLayout中两个组件的位置,java,swing,jpanel,layout-manager,grid-layout,Java,Swing,Jpanel,Layout Manager,Grid Layout,我有一个带有GridLayout和一些组件的面板。下面是一个代码示例 JPanel panel = new JPanel(); panel.setLayout(new GridLayout(5,1)); JButton[] buttons = new JButton[5]; for (int i = 0; i < buttons.length; i++) { buttons[i] = new JButton(i + ""); panel.add(buttons[i]); }

我有一个带有GridLayout和一些组件的面板。下面是一个代码示例

JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5,1));

JButton[] buttons = new JButton[5];
for (int i = 0; i < buttons.length; i++)
{
   buttons[i] = new JButton(i + "");
   panel.add(buttons[i]);
}
JPanel面板=新的JPanel();
面板设置布局(新网格布局(5,1));
JButton[]按钮=新JButton[5];
对于(int i=0;i

我想要的是能够交换这些按钮的位置。在本例中,我试图为其编写一个方法。但我做到这一点的唯一方法是将它们全部删除,然后按正确的顺序添加。那么,有没有更好的方法编写方法
swap(int index1,int index2)
来交换网格布局面板中的两个组件呢?

只删除这两个按钮,然后使用


注意:添加时顺序很重要。始终先添加较低的索引。

您尝试过吗?因为这似乎是我想做的,谢谢。谢谢,这正是我想做的。
static void swap(Container panel,
                 int firstIndex,
                 int secondIndex) {

    if (firstIndex == secondIndex) {
        return;
    }

    if (firstIndex > secondIndex) {
        int temp = firstIndex;
        firstIndex = secondIndex;
        secondIndex = temp;
    }

    Component first = panel.getComponent(firstIndex);
    Component second = panel.getComponent(secondIndex);

    panel.remove(first);
    panel.remove(second);

    panel.add(second, firstIndex);
    panel.add(first, secondIndex);
}