How does one make a component in the .CENTER of a Borderlayout occupy all center space and resize with the app?

别来无恙 提交于 2019-12-18 08:54:39

问题


My app/JFrame, using Borderlayout, has a toolbar at the top or north, a statusbar at the bottom or south and a JPanel.JTabbedPane.JScrollPane.JTable in the center. The JPanel is always a fixed size which is roughly adjustable using the various set*Size() methods applied in various combinations to the various components. But it's always a fixed size and always has east and west gaps. The north and south components stay fixed height and resize horizontally as one would expect.

Surely this is not a new or unique design.

Is this normal behaviour? Is there some trick I've missed?


回答1:


This is characteristic of retaining the default FlowLayout of JPanel and adding the panel to the center of a BorderLayout. The example below compares panels having FlowLayout, the default, or GridLayout. For contrast, the two are added to a GridLayout, which allows expansion in a manner similar to that of BorderLayout center.

import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTree;

/** @see http://stackoverflow.com/questions/5822810 */
public class LayoutPanel extends JPanel {

    public LayoutPanel(boolean useGrid) {
        if (useGrid) {
            this.setLayout(new GridLayout());
        } // else default FlowLayout
        this.add(new JTree());
    }

    private static void display() {
        JFrame f = new JFrame("LayoutPanels");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(new GridLayout(1, 0));
        f.add(new LayoutPanel(false));
        f.add(new LayoutPanel(true));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                display();
            }
        });
    }
}


来源:https://stackoverflow.com/questions/5822810/how-does-one-make-a-component-in-the-center-of-a-borderlayout-occupy-all-center

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!