Java 网格布局顺序

huangapple go评论75阅读模式
英文:

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可以为每个切换按钮共享。

代码可能如下所示:

  1. 从父面板中删除所有面板
  2. 遍历所有切换按钮,并对于每个选定的切换按钮,在末尾添加面板
  3. 对主面板进行revalidate()操作
  4. 对主面板进行repaint()操作

只有在对用户不会注意到初始删除所有面板的影响时,才会执行面板的删除/添加。

英文:

The ActionListener can be shared for each toggle button.

The code would be something like:

  1. remove all the panels from the parent panel
  2. iterate through all the toggle buttons and for each selected toggle button add back in the panel at the end
  3. revalidate() the main panel
  4. 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.

huangapple
  • 本文由 发表于 2020年8月23日 20:58:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63547236.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定