Home > Blockchain >  Checkbox too easily selectable (Java JCheckbox in JPanel with GridLayout)
Checkbox too easily selectable (Java JCheckbox in JPanel with GridLayout)

Time:12-14

I have written a Swing UI that has a JPanel with numerous controls and on the right hand side a few columns of JCheckBoxes. This is all handled by making the JPanel use a GridLayout. The problem I am having is that a given checkbox toggles it's selection status no matter where in it's grid "cell" you click in. Note, I am not using a JTable approach. The "cell" is just the rectangular area of the screen the GridLayout gave to the checkbox. It can be much bigger than the checkbox. I can't figure out how to make sure the checkboxes are only selectable when you click in the tiny box of the drawn control (not the big box of the "cell" that the checkbox is basically centered in). I've googled a lot and everyone talks about JTables. Again, I am not using a JTable. This issue is causing headaches for my users as they click on the application window and accidentally select an option!

CodePudding user response:

The GridLayout forces all UI components to fill their cell completely, so the actual checkbox only gives the illusion that it's smaller than the cell it occupies. The solution here, as with many other more complex UI designs, is to use multiple layouts nested inside one another.

In your case, try putting all your check boxes inside a BoxLayout and using glue to space them as needed. This BoxLayout should be placed side by side with your GridLayout in another enclosing container (either a JPanel or your ContentPane -- I can't say for sure because you only gave a brief description of your UI with no code or illustration).

Play around with the idea of nesting layouts until you get something you like, and don't forget to try resizing your window to see what the layout manager does under the circumstances. The final appearance isn't always exactly what you imagine it will be.

  • Related