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

问题描述 投票:0回答:1

我有一个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]);
}

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

java swing jpanel layout-manager grid-layout
1个回答
1
投票

删除这两个按钮,然后使用add method which takes an index重新添加它们。

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);
}

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

© www.soinside.com 2019 - 2024. All rights reserved.