我有一個帶有網格布局的面板,其中包含一些組件。下面是一個代碼示例。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)
1 回答

LEATH
TA貢獻1936條經驗 獲得超7個贊
僅刪除這兩個按鈕,然后使用采用索引的 add 方法重新添加它們。
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);
}
注意:添加時順序很重要。始終先添加較低的索引。
添加回答
舉報
0/150
提交
取消