为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕哥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条经验 获得超6个赞

仅删除这两个按钮,然后使用采用索引的 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 关注
  • 61 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信