gpt4 book ai didi

java - 如何让 JLabel 显示在 JButton 上?

转载 作者:行者123 更新时间:2023-12-01 18:47:39 25 4
gpt4 key购买 nike

我有一个位于 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/

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