How to make a JPanel expand to max width in another JPanel
Asked Answered
F

4

17

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.

Fiora answered 10/1, 2013 at 13:54 Comment(2)
Its non-resizable at the moment. And its already thereFiora
I am using BoxLayout as it says in the question, but i will try a borderlayout instead. Just a momentFiora
M
10

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

Mudd answered 10/1, 2013 at 14:50 Comment(1)
BorderLayout works perfectly. Thank you, and damn BoxLayout:)Fiora
T
21

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));
Taurine answered 10/1, 2013 at 13:57 Comment(6)
... or FormLayout from JGoodiesGraiae
Would that screw with the two fixed size components that shares the container?Fiora
Alternatively i would be more than satisfied by left aligning the inner component as well, but i cant seem to do so as the setAllignmentX method doesn't do squatFiora
I tried GridLayout, it did not arrange the components vertically but placed them 2 in the top and 1 in the buttomFiora
@MartinNielsen : You have to use it like new GridLayout(0, 1);Calcariferous
GridLayout makes all the components equally large. The idea was that the bottom one should only be sized after its internal components.Fiora
M
10

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

Mudd answered 10/1, 2013 at 14:50 Comment(1)
BorderLayout works perfectly. Thank you, and damn BoxLayout:)Fiora
C
4

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

Calcariferous answered 10/1, 2013 at 14:7 Comment(3)
Is there no simpler way? Keep in mind its just three components in a vertical row. It should not be required to go to the big guns. I just want my bottom component to use the full width. Surely i don't need to go gridbagconstraints for this?Fiora
@MartinNielsen : Please have a look at BoxLayout, as edited in my answer.Calcariferous
Ehm. I don't think you read the question. I AM using BoxLayout!Fiora
C
-2

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 );

     }
Corcovado answered 6/7, 2013 at 6:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.