亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

更改網格布局中兩個組件的位置

更改網格布局中兩個組件的位置

慕哥6287543 2022-09-22 19:22:57
我有一個帶有網格布局的面板,其中包含一些組件。下面是一個代碼示例。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);

}

注意:添加時順序很重要。始終先添加較低的索引。


查看完整回答
反對 回復 2022-09-22
  • 1 回答
  • 0 關注
  • 101 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號