Question

I feel I need to rephrase the question a bit.

Updated question below.

I have a JPanel that contains:

myjpanel.setLayout(new BoxLayout(selectors, BoxLayout.PAGE_AXIS));

It contains the following three panels:

JPanel with fixed size 'x' and 'y'

JPanel with no fixed size

JPanel with no fixed size and small height

The second JPanel contains a JTable so it expands to fill the full height and pushes the bottom panel all the way down, as expected.

Like this:

t
t
m
m
m
m
m
b

t = top panel, m = middle panel, b = bottom panel.

That works. But the bottom panel does not feel like filling the entire width of the parent which is a problem.

ttt
mmm
 b 

I would like either this, where the panel fills the entire width:

ttt
mmm
bbb

or this, where the bottom panel is left centered:

ttt
mmm
b

Old question below:

I have a JPanel that contains:

.setLayout(new BoxLayout(selectors, BoxLayout.PAGE_AXIS));

Within it, there are three more JPanels. The first two are of fixed size and the middle one isn't.

I want my bottom panel to take only the height it needs, but uses all the available width of the outer JPanel.

I have tried using glue but to no avail, and I would rather not set preferred and min/max sizes. Is there a way to tell the component to "Fill the entire parents width" using just the layout manager and framework. I would rather not start to do hacks like setting sizes and overriding methods.

Note: I can't put any glue or filler in the inner panel, only the outer panel and its layout manager can be modified.

Attempt 1:

Using myPanel.setLayout(new GridLayout(3, 1)); did not produce the expected results. It made a grid like this:

XX
 X

But I expected:

X
X
X

Attempt 2:

Using myPanel.setLayout(new GridLayout(0,1)); did not produce the expected results. It made a grid like this:

x
x
x

But all panels were of the same size, ignoring the restraints.

Was it helpful?

Solution 2

If using a BorderLayout and the b panel is in the SOUTH or PAGE_END it does fill the entire width.

OTHER TIPS

The easiest way would be to use another layout manager such as GridLayout that automatically sizes components to fill the parent container.

myPanel.setLayout(new GridLayout(0, 1));

You can use GridBagLayout, for that, using

gridBagObject.fill = GridBagConstraints.HORIZONTAL

One example for your help, relating to GridBagLayout.

As asked in comments, related to that

The BoxLayout is another alternative, that respects the preferred sizes of the components. You can try that if GridBagLayout is that tough :-)

Code with GridBagLayout, for more clarity :

import javax.swing.*;
import java.awt.*;

/**
 * Created with IntelliJ IDEA.
 * User: Gagandeep Bali
 * Date: 1/10/13
 * Time: 7:43 PM
 */
public class GridBagExample
{
    private void displayGUI()
    {
        JFrame frame = new JFrame("GridBagLayout Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        CustomPanel topPanel = new CustomPanel(Color.BLUE.darker().darker());
        CustomPanel middlePanel = new CustomPanel(Color.CYAN.darker().darker());
        CustomPanel bottomPanel = new CustomPanel(Color.DARK_GRAY);

        JPanel contentPane = new JPanel();
        contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.FIRST_LINE_START;
        gbc.fill = GridBagConstraints.VERTICAL;
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.weighty = 0.3;

        contentPane.add(topPanel, gbc);

        gbc.gridy = 1;
        contentPane.add(middlePanel, gbc);

        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.BOTH;
        contentPane.add(bottomPanel, gbc);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new GridBagExample().displayGUI();
            }
        });
    }
}

class CustomPanel extends JPanel
{
    public CustomPanel(Color backGroundColour)
    {
        setOpaque(true);
        setBackground(backGroundColour);
    }

    @Override
    public Dimension getPreferredSize()
    {
        return (new Dimension(200, 150));
    }
}

OUTPUT :

GridBagExampleOutput

Here some custom JPanel is used to expanding and shrinking with static input values.
Java timer is using to Delay and speed up the panel display time.

 public class SlidingPanel extends JPanel {
 private int paneHeight;
 private int paneWidth;
 private int comHeight;
 private int comWidth;
 private Timer everyspeedmillisec;

/**custom class for slide up and down actions for JPanel
 * 
 */

public SlidingPanel(LayoutManager layout,Dimension panedim) {

    super(layout);  
    setPreferredSize(panedim);
    paneHeight = (int)panedim.getHeight();;
    paneWidth  = (int) panedim.getWidth(); 

}

    /**function for expanding Jpanel
 * 
 */

public void expand_sft_det(int speed ,JPanel slidingcom)
{

 //Add Jpanel for sliding 

    this.add(slidingcom);

//Get height and width for panel ,that what we want to display as slide height.

 comHeight=(int)slidingcom.getMinimumSize().getHeight();

 comWidth=(int) slidingcom.getMinimumSize().getWidth(); 

//Intializing timer with some static values - Medium speed)

   everyspeedmillisec = new Timer(30, new ActionListener() {


       private int count_timer=0; 

       public void actionPerformed(ActionEvent e) {

       count_timer++;

         if( paneHeight < comHeight){

             setPreferredSize(new Dimension(paneWidth, paneHeight));

             paneHeight+=20;

             repaint();

             revalidate();

         }
         else

             everyspeedmillisec.stop() ;
    }


  });


  everyspeedmillisec.start(); 


}

/**function for Shrinking Jpanel * */

public void shrink_sft_det(int speed ,JPanel slidingcom) {

 comHeight    = (int)slidingcom.getMinimumSize().getHeight();

     comWidth     = (int)slidingcom.getMinimumSize().getWidth();

//height for slide up to top position

     paneHeight=0;

     everyspeedmillisec = new Timer(30, new ActionListener() {

     private int count_timer=0;

 public void actionPerformed(ActionEvent e) {

     count_timer++; 

     if( paneHeight < comHeight){

           setPreferredSize(new Dimension(comWidth,comHeight));

           comHeight-=20;

           repaint();

           revalidate();

     }
     else
       everyspeedmillisec.stop() ;

 }

});
everyspeedmillisec.start(); 

}

//Declare class and using shrinking onclick event

public class SoftPanel extends JPanel implements ActionListener
, MouseListener {

JPanel MoredetPane;

JPanel SlidedetPane;

private JLabel SoftDOCLabel;

private JLabel SoftLocation;

private JLabel SoftUpdates;

private boolean mr_det_flag =true;



MoredetPane = new SlidingPanel(new GridLayout(1,1,5,5),new Dimension(300,1));

MoredetPane.setOpaque(false);

//Add some components 

        SlidedetPane = new JPanel(new GridLayout(3,2,50,25));

        SlidedetPane.setPreferredSize(new Dimension(300,200));

        SlidedetPane.setOpaque(false);

                SoftDOCLabel = new JLabel("Software Date") ;

            SoftLocation = new JLabel("Software Location") ;

        SoftUpdates  = new JLabel("Software Updates") ;


        SlidedetPane.add(SoftDOCLabel);

        SlidedetPane.add(new JLabel(softbean.getSoftDOC()));

        SlidedetPane.add(SoftLocation);

        SlidedetPane.add(new JLabel(softbean.getSoftPath()));  

        SlidedetPane.add( SoftUpdates);

        SlidedetPane.add(new JLabel(""));  

//Onclick events

      modedetails_Label.addMouseListener(new MouseAdapter() {


       @Override
       public void mousePressed(MouseEvent clickeve) {

           if(mr_det_flag){

              mr_det_flag=false;

                  ((SlidingPanel)MoredetPane).expand_sft_det(200,SlidedetPane);

                  add(SlidingPanel);
            }
            else{

            mr_det_flag=true;

          ((SlidingPanel) MoredetPane).shrink_sft_det(0,SlidedetPane);

            }


          });


    add( MoredetPane );

     }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top