设置大小后 JLabel.setText() 不起作用
我有一个 JLabel,需要在按下按钮时动态更改。我正在使用 JLabel.setText(s)
但是,它不起作用。我尝试过: 我
JLabel.repaint()
JLabel.validate()
JLabel.revalidate()
发现奇怪的是,当我不使用以下任何一项设置 JLabel 的大小时,它工作正常:
JLabel.setPrefferedSize()
JLabel.setMinimumSize()
JLabel.setSize()
任何人都可以帮助我解释为什么在我设置其中一个大小属性后它不起作用?
I have a JLabel that I require to change dynamically when a button is pressed. I am using JLabel.setText(s)
However, it is not working. I've tried:
JLabel.repaint()
JLabel.validate()
JLabel.revalidate()
The thing I find strange is that it works fine when I don't set the size of the JLabel using any of:
JLabel.setPrefferedSize()
JLabel.setMinimumSize()
JLabel.setSize()
Can anyone help me with why it isn't working after I set one of the size properties?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的按钮正在执行的操作可能是一项非常漫长的任务,并且您希望让用户了解该过程。
为此,您必须创建一个新线程来执行长任务,并且当您为标签设置新文本时,将
label.setText()
语句包装到invokeLater()
代码>:What your button is doing is probably a very long task and you want to keep the user informed about the process.
To do this you have to create a new Thread which performs the long task and when you set new text to your label, wrap the
label.setText()
statement into aninvokeLater()
:对于 Swing 中组件的大小调整,最终父容器的布局对组件的大小有最终决定权。
例如,在
FlowLayout
中,在组件上调用setPreferredSize()
、setSize()
或setMaximumSize()
所有这些的结果都是给标签指定尺寸,而不是超出它的尺寸。但是,使用setMinimumSize()
,它将从该尺寸开始,然后是高于该尺寸的尺寸。对于
BorderLayout
,如果将组件添加到中心,则任何调整大小的方法都不会影响该组件 - 它只会占用最大的可用空间。如果将父容器的布局设置为
null
,您可以显式调整组件的大小,但是,您将失去其他布局所具有的自动调整大小的功能。For sizing components in Swing, ultimately the layout of the parent container has the final say on the size of the component.
For example, in
FlowLayout
, callingsetPreferredSize()
,setSize()
, orsetMaximumSize()
on a component all have the result of giving the label that size, and not sizing over it. However, withsetMinimumSize()
it will start at that size, then size above it.For
BorderLayout
, if the component is added to the center, none of the sizing methods affect the component - it just takes the maximum amount of space available.If you set the layout of the parent container to
null
you can explicitly size components, however, you will lose the automatic resizing that you have with other layouts.弄清楚我的问题,
我正在使用:
我更改为:
Figured out my problem,
I was using:
I changed to:
当您在此处设置首选尺寸时,JLabel 的高度不得预先设置:),如果您在设置高度后尝试相同的行,我认为它应该可以正常工作。
有时还需要
JPanel.updateUI();
来刷新显示的 UI。在此处输入代码
As you are setting the preferred size here, the height of JLabel must not have been previously set :), if you try the same line after setting the height, I think it should work well.
Also sometimes
JPanel<xx>.updateUI();
is required to refresh the displayed UI.enter code here