作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个位于 JButton 之上的 JLabel,但它不会显示在顶部。当 JButton 的代码被注释掉时,就会显示 JLabel,这意味着它在那里,但位于底部。有没有办法在 JButton 之上显示 JLabel?
任何帮助都会很棒。谢谢!
import java.awt.*;
import javax.swing.*;
public class TestingLabelsOverButtons extends JFrame
{
public static void main (String []args)
{
new TestingLabelsOverButtons();
}
public TestingLabelsOverButtons()
{
super();
setSize(500,500);
Container c = getContentPane();
c.setLayout(null);
c.setBackground(Color.white);
JButton button = new JButton("Button");
button.setBounds(0,0,500,500);
c.add(button);
JLabel label = new JLabel("Label");
label.setBounds(0,0,500,500);
c.add(label);
setVisible(true);
}
}
编辑:
为了澄清,我的游戏需要这个,当单击按钮时,JLabel 将显示在按钮顶部以显示添加的“分数”。在我的游戏中,JLabel 将是一个比 JButton 小的正方形,因此 JButton 仍然需要可见。
最佳答案
基于组件的 ZOrder 绘制组件。基本上最后添加的组件首先被绘制。
所以你可以通过这样做来实现你想要的:
c.add(button);
c.add(label);
尽管如此,我同意这些评论。你想做什么?可能有更好的解决方案。使用 setBounds() 来定位和调整组件的大小几乎从来都不是一个好主意。
I need this for my game where when the button is clicked, a JLabel will be shown ontop of the button to display a "score" that is added.
如果您要强制用户单击按钮来显示分数,那么您可能应该使用 JOptionPane
来显示标签。不然标签怎么会消失呢?强制用户单击同一个按钮并不是一个很好的 UI。
关于java - 如何让 JLabel 显示在 JButton 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17058159/
我是一名优秀的程序员,十分优秀!