Search code examples
javaswinglayout-managergrid-layout

Why can't GridLayout allow components to be changed by row and column?


This is perhaps more of a whine than a question, and I'm aware there's a workaround to the problem described in this post. But I have a situation where I have to add components to a GridLayout, possibly enlarging the grid as I go; but the components don't get created and inserted in a nice neat order; and I don't know when I'm done being handed components to insert into the grid. In other words, in a 3x3 grid I might get handed a component to put at (0,2) and then another at (1,0) and then one at (0,0). And then I might get one at (5,2) and need to enlarge the grid. And then I might get told to replace the line at (0,0) with something else.

I understand that there's no way to say "put a component at x, y". I get that I'm going to have to build a 2D array to hold my components and then empty and refill the grid from the array, each time it changes, which is going to be quite often in several large grids, so I'd rather not. I get that life is like that and the language is the language and who am I to question why.

But I'm really curious. This seems like the most basic of operations for a grid to support. Not having it feels like I'm working with a spreadsheet that only lets you enter values in order from left to right - it's simple madness.

I haven't taken apart the source code for GridLayout, but any naive understanding of how it "must work" makes me think add(component, row, col) should be trivial to implement. It must not be, because GridLayout isn't exactly new and I can't believe I'm the first to think random access to a grid is a good idea. So it must be really hard. But why?

I realize understanding why the internals of GridLayout can't support this, doesn't solve any real problems, except the problem of me unable to stop thinking about how fundamentally weird the restriction is. In the end I'm going to end up with a parallel array, or messing with the more complex GridBagLayout, unless someone knows a better way. But I just want to know why I have to.


Solution

  • Why not approach the problem from a different angle:

    • Create your grid using GridLayout
    • Fill the grid with empty JPanels
    • JPanels that each uses a BorderLayout
    • Keep these JPanels where they are
    • But swap the JPanels that they display within them in each of their BorderLayout.CENTER positions

    Alternatively, you could have them use a CardLayout, but the effect would be the same