首页 > 解决方案 > 根据 JFrame 大小调整 JPanel 宽度

问题描述

我想知道是否有一种方法可以通过从框架大小中获取面板的宽度来调整面板的宽度,而对于高度值,我想保留默认值。

提前致谢!

标签: javaswingjframejpanellayout-manager

解决方案


使用BorderLayout卢克!

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;

public class BorderLayoutExample {

    public static void main(String[] args) {
        JTextArea area = new JTextArea(15, 40);
        JFrame frm = new JFrame("Horizontal resizing");
        // not required, because the default layout here is the BorderLayout.
        // but in common case you probably need to do it.
        frm.setLayout(new BorderLayout());
        // Use BorderLayout.SOUTH - when you want that the top space will not be unused.
        frm.add(new JScrollPane(area), BorderLayout.NORTH);
        frm.pack();
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }
}

调整框架大小时,只会修改文本区域的宽度。有关更多信息,请阅读布局管理器


推荐阅读