Layout manager preferredSize Java

I'm still trying to learn how layout manager works I made a frame with two jpanels

I set the preferredSize of each panel accordingly and packaged them, but I got unexpected results

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

public class LayoutMgrTest
{
    public static void main(String[] args)
    {
        TableBasic frame = new TableBasic();
        frame.setDefaultCloSEOperation( EXIT_ON_CLOSE );
        frame.setVisible(true);


        frame.getContentPane().setLayout(new GridLayout(2,1));

        JPanel controlPane = new JPanel();
        JPanel buttonPane = new JPanel();

        controlPane.setLayout(new @R_985_2419@Layout(controlPane,@R_985_2419@Layout.PAGE_AXIS));
        controlPane.setPreferredSize(new Dimension(200,200));
        controlPane.add(new JScrollPane(new JTextArea()));

        buttonPane.setLayout(new FlowLayout(FlowLayout.LEFT));
        buttonPane.setPreferredSize(new Dimension(100,20));
        buttonPane.add(new JButton("Button1"));
        buttonPane.add(new JButton("Button2"));

        frame.getContentPane().add(controlPane,BorderLayout.NORTH);
        frame.getContentPane().add(buttonPane,BorderLayout.soUTH);
        frame.setSize(new Dimension(500,500));
        frame.pack();
    }
}

No matter what I do, if I use grid layout, it always seems to allocate half of the available space for each control I was told:

The height of the button panel is 20 Its distribution far exceeds it:

What's wrong with this code? I'd like to keep two jpanels, please It's easy to simply add text boxes and buttons directly to the frame, but I need to use jpanels (because I'm going to add borders and other things)

Solution

This is the result of using GridLayout as the layout manager Change it to borderlayout:

frame.getContentPane().setLayout(new BorderLayout());

For example, this code (I changed a little from the original):

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

public class LayoutMgrTest
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloSEOperation( JFrame.EXIT_ON_CLOSE );
        //frame.setVisible(true);   
        //frame.getContentPane().setLayout(new BorderLayout());

        JPanel controlPane = new JPanel();
        JPanel buttonPane = new JPanel();

        controlPane.setLayout(new @R_985_2419@Layout(controlPane,40));
        buttonPane.add(new JButton("Button1"));
        buttonPane.add(new JButton("Button2"));

        frame.add(controlPane,BorderLayout.NORTH);
        frame.add(buttonPane,BorderLayout.soUTH);
        //frame.setSize(new Dimension(500,500));
        frame.pack();
        frame.setVisible(true);
    }
}

Generate this framework:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>