简体   繁体   English

如何让JLabel显示在JButton之上?

[英]How do I get a JLabel to show over a JButton?

I have a JLabel that is ontop of a JButton, but it will not show up ontop. 我在JButton的顶部有一个JLabel,但它不会在顶部显示。 When the code for the JButton is commented out, the JLabel is shown, meaning that it is there but is on the bottom. 注释掉JButton的代码后,将显示JLabel,这意味着它在其中,但在底部。 Is there a way to show the JLabel ontop of the JButton? 有没有办法在JButton的顶部显示JLabel?

Any help would be awesome. 任何帮助都是极好的。 Thank you! 谢谢!

    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);
        }
    }

EDIT: 编辑:

For clarification, 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. 为了澄清起见,我需要在游戏中使用该按钮,单击该按钮时,按钮上方会显示一个JLabel,以显示添加的“得分”。 In my game, the JLabel will be a smaller square than the JButton, so the JButton still needs to be visible. 在我的游戏中,JLabel将比JButton小,因此JButton仍然需要可见。

Swing paint components based on the ZOrder of the component. 根据组件的ZOrder摆动绘画组件。 Basically the last component added is painted first. 基本上,最后添加的组件先绘制。

So you could achieve what you want by doing: 因此,您可以通过执行以下操作来实现所需的功能:

c.add(button);
c.add(label);

Although, I agree with the comments. 虽然,我同意这些意见。 What are you trying to do? 你想做什么? There is probably a better solution. 可能有更好的解决方案。 It is almost never a good idea to be using setBounds() to position and size a component. 使用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. 对于我的游戏,在单击按钮时,它会需要一个JLabel,以显示添加的“分数”。

If you are going to force the user to click a button to display the score then you should probably be using a JOptionPane to display the label. 如果要强制用户单击按钮以显示分数,则可能应该使用JOptionPane来显示标签。 Otherwise how will the label disappear? 否则标签将如何消失? Forcing the user to click on the same button is not a very good UI. 强迫用户单击同一按钮不是一个很好的UI。

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

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