java - 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);
}
}
解决方案
首先,变量名不应以大写字符开头。学习并遵循 Java 约定。
我尝试添加 setSize()
不要试图玩弄大小。布局管理器负责确定每个组件的大小和位置。
您也不应该尝试“设置”组件的首选大小。所有 Swing 组件都根据组件的属性确定自己的首选大小。
您可以通过更改组件的属性来影响组件的首选尺寸计算。
对于您可以使用的所有组件:
setFont(..)
- 使文本更大setBorder( new EmptyBorder(...) )
- 在 4 个边界周围留出额外空间。可以为单个组件设置边框,也可以在 JPanel 上为添加到面板的所有组件设置边框。
此外,对于 JList,您可以使用:
setPrototypeCellValue( "Page 0000" )
- 根据您指定的文本计算更大的首选宽度
阅读 API,您可能会发现可以更改的其他属性。
推荐阅读
- regex - Perl 中的开始和结束
- c# - C# ListBox 项自动更改颜色
- python - 我需要帮助将图像和音频剪辑组合成 1 个视频
- php - 我使用“将联系表格 7 数据保存到自定义数据库而不是 wordpress 数据库方法,并且文件上传不再保存到目录
- excel - 尝试将值小于零的单元格格式化为逗号
- jquery - Bootrap-Select 不能在多个值上选择
- sql - 如何使用一个查询提取当前日期和下一个日期
- java - 是否可以通过 Java 中的 Telegram API 发送邮件(不是机器人)
- vb.net - 尝试使用 Blue Prism 对 HTTP 请求令牌进行 API 时出现错误“字典中不存在给定的密钥”
- python - 如何在期望脚本中读取发送命令输出