Search code examples
javaswingjpanellayout-managerboxlayout

Using BoxLayout to resize JPanels in GUI


I currently have this code I am working with:

this.getContentPane().add(wwjPanel, BorderLayout.EAST);
        if (includeLayerPanel)
        {
            this.controlPanel = new JPanel();
            controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.Y_AXIS));
            this.layerPanel = new LayerPanel(this.getWwd());
            this.controlPanel.add(new FlatWorldPanel(this.getWwd()),Box.createRigidArea(new Dimension(1000, 1000))); //This is the top pan
            this.controlPanel.add(this.getStates(), Box.createRigidArea(new Dimension(0, 100)));
            this.controlPanel.add(this.getPanelAlerts(), Box.createRigidArea(new Dimension(0,100)));

            this.getContentPane().add(this.controlPanel, BorderLayout.WEST);//This is the whole panel on the left
        }

I am trying to resize the JPanels, called controlPanel here, to each have their own unique size in my GUI. I am new to building GUIs with java, and the majority of the code I have is pulled from another file. The code I am trying to incorporate are these new panels as described in my code, and trying to resize them. Is BoxLayout what I want to be using to get my desired effect?

Also, when I use the createRigidArea it seems to work, but if I continue to change the x and y values you pass to it nothing seems to happen. What I mean by this is, that I don't see any visual difference by changing the values, and I have used values ranging from 0-1000.

Thanks.


Solution

  • this.controlPanel.add(new FlatWorldPanel(this.getWwd()),Box.createRigidArea(new Dimension(1000, 1000))); 
    

    The Box.createRigidArea(...) isn't doing anything. The second paramater of the add(...) method is a constraint to be used by the layout manager and a BoxLayout doesn't expect any constraint so it should be ignored.

    If you want vertical space between the vertically stacked panels then you need to add it as a separate component and you would probably use Box.createVerticalStrut():

    this.controlPanel.add(new FlatWorldPanel(this.getWwd()));
    this.controlPanel.add(Box.createVerticalStrut( 50 ));
    

    The size of the FlatWorldPanel, is determined by the components you add to it.

    Read the section from the Swing tutorial on How to Use BoxLayout for more information and working examples.