jButton 在更改文本标签时调整大小
我对 java GUI 相当陌生,并且一直在使用 netbeans 来帮助我。
我已经设置了一个 jButton,当单击它时,它的标签会发生变化。我的问题是,尽管设置了最大和最小尺寸以及设置了 PreferredSize 方法,按钮的尺寸仍拒绝保持固定。我需要更改布局吗?我应该仔细检查并将每个按钮放置在面板上还是有更简单的方法?
我觉得这应该是一个很容易解决的问题,但我已经解决了一个多小时了。我将不胜感激任何想法。谢谢
I'm reasonably new to java GUIs and have been using netbeans to help me out.
I've set up a jButton such that when clicked its label changes. My issue is that the size of the button refuses to remain fixed despite setting a maximum and minimum size as well as the setting the preferredSize method. Do I need to change my layout? Should I go through and place each button on a panel or is there a simpler way?
I feel like this should be an easy problem to fix yet I've been at it for over an hour now. I'd appreciate any ideas. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有多种方法可以处理此问题:
一种干净且简单的方法是创建 不同按钮的图像图标,使它们具有相同的大小。这使您可以完全控制它们的外观。
实现此目的的一种快速而肮脏的方法是添加空格,直到按钮大小大致相同。这并不完美,因为 JButons 上显示的字体通常不是固定宽度的。
“正确的”Swing 方式是使用自定义布局。例如,如果您使用 GridBagLayout 来排列组件,并将 JButton 的“weightx”和“weighty”设置为 1.0,那么它将占用尽可能多的空间,从而保持相同的大小。
There are a number of ways to handle this:
A clean and easy way would be to create image icons for the different buttons, making them the same size. This lets you completely control what they will look like.
A quick-and-dirty way to do this is the add spaces until the buttons are approximately the same size. This won't be perfect because the fonts that appear on JButons are typically not fixed-width.
The 'proper' Swing way would be to use a custom Layout. For instance, if you use a GridBagLayout to arrange your components, and set the 'weightx' and 'weighty' for the JButton to 1.0, then it will take up as much space as possible, which will keep it the same size.