Search code examples
javadynamicgridlayoutmanager

Java GridLayout how to dynamically change grid layout


I am trying to create a character sheet program that arranges 3 panels based on how wide the frame is. If the frame is not very wide, I want the panels to be arranged vertically, but if the user chooses to make the frame wider, I would like to arrange the panels horizontally.

I also have a scrollPanel that the 3 panels are arranged on, so the scrollPanel is being added to a scrollPane.

I have seen posts that say that an eventlistener would work, however most of these are for buttons, and I need the Frame size to pass a certain threshold before the layout changes. I seen other posts that recommend html which I don't see as necessary right now.

enter image description here

So in this picture the 3 panels are arranged vertically, and are able to be scrolled through.

    scrollPanel.add(leftPanel); //this is the yellow panel that is being added
    scrollPanel.add(centerPanel); //this one is farther down
    scrollPanel.add(rightPanel); //even farther down
    scrollPanel.setBackground(Color.CYAN);
    scrollPanel.setLayout(new GridLayout(0, 1)); //so here I would like to have an if statement or event swap the 0 and the 1.

Summary:

  • Can I change a GridLayout dynamically based on the size of a Frame?

  • How do I monitor for a Frame size change? event? if statement?

  • Can I do the same with a ScrollPane with setting the horizontal and vertical scroll bars to never appear based on if the panels are vertical or horizontal?


Solution

  • You can change the GridLayout as follows:

    gr.setRows(newR);
    gr.setColumns(newC);
    myFrame.validate();
    

    where gr is the layout you created somewhere and newR/newC are the new numbers of rows/columns.

    Or you can say

    gr=new GridLayout(newR, newC);
    myFrame.setLayout(gr);
    

    Then

    if(myFrame.getWidth()>thershold) {
    
    .. do the above
    
    }