Search code examples
javaswinglayout-managergrid-layoutflowlayout

Best Swing Layout for 2-dimensional grid of buttons?


I'm trying to create a JDialog like the Symbol dialog in Microsoft Word that you get by choosing Symbol... from the Insert menu. Basically, it's an n x m (n and m are not known until runtime) grid of small buttons. I've got a first version of this working nicely using a GridLayout. The problem is that when you resize the dialog (and there is a requirement that you should be able to resize it), the size of the buttons changes. I need the size of the buttons to remain constant.

But I want the dimensions of the grid containing the buttons to change. For example, if the dialog gets wider, but stays the same height, the number of rows should lessen, while the number of columns increases.

I've thought of a couple of ways to fix this:

  1. When the dialog is resized, create a new GridLayout and repopulate it with the buttons. I'm going to try this and see how it looks, but it seems like a clumsy way of doing it.
  2. Use some other type of layout such as a FlowLayout. I took a stab at this, but it put all n x m buttons in one row. I do not want to use horizontal scroll-bars and the buttons ran off the right edge. Anyway, it's supposed to be a 2-dimensional grid of buttons.

What is the best way to solve this layout problem?


Solution

  • if the dialog gets wider, but stays the same height, the number of rows should lessen, while the number of columns increases.

    Wrap Layout might be what you are looking for.