简体   繁体   English

jButton在更改文本标签时调整大小

[英]jButton resizing upon changing text label

I'm reasonably new to java GUIs and have been using netbeans to help me out. 我是java GUI的新手,并且一直使用netbeans来帮助我。

I've set up a jButton such that when clicked its label changes. 我已经设置了一个jButton,当点击它的标签时会改变。 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. 我的问题是,尽管设置了最大和最小尺寸以及设置preferredSize方法,按钮的大小仍然保持固定。 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 谢谢

  1. If you are new to Swing don't use a GUI builder as you will run into all sorts of issues like this one. 如果您是Swing的新手,请不要使用GUI构建器,因为您会遇到类似这样的各种问题。
  2. It sounds like your Layout is preventing resizing. 听起来你的布局正在阻止调整大小。 Make sure you are using the correct Layout Manager for your designed look. 确保使用正确的布局管理器来实现您的设计外观。 Double check any constraints that you have set for the layout. 仔细检查您为布局设置的任何约束。 You could experiment with a different layout manager like FlowLayout to check to make sure your setPreferredSize () calls are working correctly etc. 您可以尝试使用不同的布局管理器(如FlowLayout)来检查以确保您的setPreferredSize()调用正常工作等。

There are a number of ways to handle this: 有很多方法可以解决这个问题:

  1. 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. 这使您可以完全控制它们的外观。

  2. 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. 这并不完美,因为JButons上出现的字体通常不是固定宽度。

  3. The 'proper' Swing way would be to use a custom Layout. '正确'的Swing方式是使用自定义布局。 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. 例如,如果您使用GridBagLayout来排列组件,并将JButton的'weightx'和'weighty'设置为1.0,那么它将占用尽可能多的空间,这将保持相同的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM