更改网格布局中两个组件的位置

我有一个带有网格布局的面板,其中包含一些组件。下面是一个代码示例。


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)


慕哥6287543
浏览 105回答 1
1回答

LEATH

仅删除这两个按钮,然后使用采用索引的 add 方法重新添加它们。static void swap(Container panel,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;int firstIndex,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;int secondIndex) {&nbsp; &nbsp; if (firstIndex == secondIndex) {&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; if (firstIndex > secondIndex) {&nbsp; &nbsp; &nbsp; &nbsp; int temp = firstIndex;&nbsp; &nbsp; &nbsp; &nbsp; firstIndex = secondIndex;&nbsp; &nbsp; &nbsp; &nbsp; secondIndex = temp;&nbsp; &nbsp; }&nbsp; &nbsp; Component first = panel.getComponent(firstIndex);&nbsp; &nbsp; Component second = panel.getComponent(secondIndex);&nbsp; &nbsp; panel.remove(first);&nbsp; &nbsp; panel.remove(second);&nbsp; &nbsp; panel.add(second, firstIndex);&nbsp; &nbsp; panel.add(first, secondIndex);}注意:添加时顺序很重要。始终先添加较低的索引。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java