gpt4 book ai didi

java - 如何让 JButton 填充他的父 BoxLayout

转载 作者:行者123 更新时间:2023-11-30 06:11:34 26 4
gpt4 key购买 nike

JFrame frame = new JFrame();
frame.setSize(400, 300);
JPanel panel = new JPanel() {{
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(new JButton("button"));
add(new JTextField("Text"));
}};

frame.setContentPane(panel);
frame.setVisible(true);

我想让 JButton 像 JTextField 一样填充父布局。那么什么属性控制它呢?

最佳答案

I want to make JButton fill parent layout like JTextField. So what property controlled it?

BoxLayout 尊重组件的“最大尺寸”。

按钮的最大尺寸是其“首选尺寸”,因此如果您希望按钮变大,则需要重写按钮的 getMaximumSize() 方法以返回至少为框架的大小。

或者正如评论中提到的,您可以使用:

  1. 一个 GridLayout 使所有组件具有相同的大小
  2. 一个GridBagLayout,允许组件根据需要增长。

阅读 Swing 教程中关于 Using Layout Managers 的部分有关上述内容的更多信息。

关于java - 如何让 JButton 填充他的父 BoxLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50129945/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com