英文:
Java Grid Layout Order
问题
我有三个切换按钮,可以打开/关闭网格布局中的三个面板,我们称它们为面板 A、B 和 C。
我想实现无论我以什么顺序打开面板,它们最终都会按顺序排列(A B C)。目前,我只是使用 add()
,它将项目添加到末尾,这意味着它们的顺序与我点击按钮的顺序相同。
根据活动按钮的数量,我正在更新正确数量的行和列的网格布局。
使用 add(jPanel, 0, n)
,其中 n 为 0、1、2(对应 A、B、C 面板)会在我使用超过行数或列数的索引时抛出非法组件位置异常。
英文:
I have 3 toggle buttons which can turn on/off three panels in a grid layout, let's call them panels A, B, and C.
I want to achieve that no matter what order I turn the panels on, they will end up in order (A B C). Right now, I just use add()
which adds the item to the end meaning they end up in the same order I clicked the buttons.
I am updating the grid layout with the right number of rows and cols depending on how many buttons are active
Using add(jPanel, 0, n)
where n is 0, 1, 2 for the A, B, and C panels throws an illegal component position exception when I use an index which exceeds the number of rows or cols
答案1
得分: 1
ActionListener可以为每个切换按钮共享。
代码可能如下所示:
- 从父面板中删除所有面板
- 遍历所有切换按钮,并对于每个选定的切换按钮,在末尾添加面板
- 对主面板进行revalidate()操作
- 对主面板进行repaint()操作
只有在对用户不会注意到初始删除所有面板的影响时,才会执行面板的删除/添加。
英文:
The ActionListener can be shared for each toggle button.
The code would be something like:
- remove all the panels from the parent panel
- iterate through all the toggle buttons and for each selected toggle button add back in the panel at the end
- revalidate() the main panel
- repaint() the main panel
The removing/adding of the panels will only occur when the revalidate()/repaint() is done to the user won't notice any effect of the inital removing of all the panels.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论