开发者

java Box.glue not working as expected

开发者 https://www.devze.com 2023-03-23 07:30 出处:网络
I am writing a class where I want to be able to add an unknown number of panels to another JPanel in a vertical BoxLayout. theses panels each consist of a label as a title and another panel. I want th

I am writing a class where I want to be able to add an unknown number of panels to another JPanel in a vertical BoxLayout. theses panels each consist of a label as a title and another panel. I want the panels that are added to all be located at the top of the panel (in this case Gui) so I added vertical glue at the bottom. I had everything working as expected until I needed to redo some of the code in order to place the main panel (represented by gui) in a scrollpane. for the sake of simplicity I was able to duplicate my problem in the following code. when run you will notice that the glue does not take the empty space but it is rather divided between the other panels. I have set a size for the jframe rather then used .pack() to illustrate the point.

public class Gui extends JFrame {

public Gui() {
    getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_A开发者_开发百科XIS));
    getContentPane().add(new Panel());
    getContentPane().add(new Panel());
    getContentPane().add(new Panel());
    getContentPane().add(new Panel());
    getContentPane().add(Box.createVerticalGlue());
}

public class Panel extends JPanel{

    public Panel(){
        this.setLayout(new BorderLayout());
        this.add(new JLabel("Title"), BorderLayout.NORTH);
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
        this.add(panel);
        panel.add(new JButton("button"));
    }
}
public static void main (String[] args){
    Gui g = new Gui();
    g.setSize(240, 320);
    g.setLocationRelativeTo(null);
    g.setVisible(true);
    g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}


If you invoke this.setBorder(BorderFactory.createLineBorder(Color.BLACK)) within the Panel class and panel.setBorder(BorderFactory.createLineBorder(Color.RED)) on the nested JPanel, you'll see that there is no "empty space" between those components.


java Box.glue not working as expected


EDIT

By replacing the layout manager of Panel with BoxLayout, you'll get the following -

java Box.glue not working as expected

To be honest, you'll just need to play around with your layout managers. I recommend you read Laying Out Components Within a Container before you proceed any further with Swing.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号