简体   繁体   中英

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. When the code for the JButton is commented out, the JLabel is shown, meaning that it is there but is on the bottom. Is there a way to show the JLabel ontop of the JButton?

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. In my game, the JLabel will be a smaller square than the JButton, so the JButton still needs to be visible.

Swing paint components based on the ZOrder of the component. 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.

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.

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. Otherwise how will the label disappear? Forcing the user to click on the same button is not a very good UI.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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