首页 > 解决方案 > Java BorderLayout:如何设置组件的首选大小

问题描述

我有一个带有两个面板的框架,一个名为 ScreenPanel,一个名为 MenuPanel,两者都有边框布局管理器。ScreenPanel 是 JFrame 的内容面板。菜单面板位于 ScreenPanel 的西边。但是,当我运行时,MenuPanel 的宽度太小,我尝试添加 setSize(); 到 MainPanel 及其所有组件,但这不起作用,有没有办法可以在 BorderLayout 中设置 MenuPanel 的大小?

菜单面板:

DefaultListModel<String> MenuModel = new DefaultListModel<>();
JList<String> MenuList = new JList<>(MenuModel);
JLabel MenuLabel = new JLabel();
MenuPanel(){
    setBackground(new Color(0,168,243));
    setLayout(new BorderLayout());

    MenuList.setBackground(new Color(0,200,250));
    MenuList.setForeground(new Color(80,80,80));
    MenuList.setFont(new Font("Arial",Font.BOLD,20));

    MenuModel.addElement("Page 1");
    MenuModel.addElement("Page 2");
    MenuModel.addElement("Page 3");
    MenuModel.addElement("Page 4");
    MenuModel.addElement("Page 5");

    MenuLabel.setText("Menu");
    MenuLabel.setFont(new Font("Arial",Font.BOLD,50));
    MenuLabel.setForeground(new Color(50,50,50));

    add(MenuList,BorderLayout.CENTER);
    add(MenuLabel,BorderLayout.NORTH);

屏幕面板:

public class ScreenPanel extends JPanel{
     ScreenPanel(){
         setLayout(new BorderLayout());
         setBackground(new Color(230,230,230));
         add(new MenuPanel(),BorderLayout.WEST);
     }
 }

框架:

 public class ScreenFrame extends JFrame{
     ScreenFrame(){
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setExtendedState(Frame.MAXIMIZED_BOTH);
         setContentPane(new ScreenPanel());
        setTitle("Random Project");
     }
 }

主要方法:

 public class Main {
     public static void main(String[] args) {
         ScreenFrame screen = new ScreenFrame();
         screen.pack();
         screen.setVisible(true);
     }
 }

期待: 在此处输入图像描述

现实: 在此处输入图像描述

标签: javaswingborder-layout

解决方案


首先,变量名不应以大写字符开头。学习并遵循 Java 约定。

我尝试添加 setSize()

不要试图玩弄大小。布局管理器负责确定每个组件的大小和位置。

您也不应该尝试“设置”组件的首选大小。所有 Swing 组件都根据组件的属性确定自己的首选大小。

您可以通过更改组件的属性来影响组件的首选尺寸计算。

对于您可以使用的所有组件:

  1. setFont(..)- 使文本更大
  2. setBorder( new EmptyBorder(...) )- 在 4 个边界周围留出额外空间。可以为单个组件设置边框,也可以在 JPanel 上为添加到面板的所有组件设置边框。

此外,对于 JList,您可以使用:

  1. setPrototypeCellValue( "Page 0000" )- 根据您指定的文本计算更大的首选宽度

阅读 API,您可能会发现可以更改的其他属性。


推荐阅读