Question

I have a grid of 16 buttons which will represent dice. When a score is added, I want a JLabel to pop up in the middle and display the added score. The 16 buttons and one label are all within one JLabel. Why do the buttons always show on top of the JLabel, even when the JLabel is set to visible?

Thank you for any help!


Pictures

JButtons visible, JLabel is not:
http://i.stack.imgur.com/0r5h2.png

When the JButtons are setVisible to false, the JLabel is seen:
http://i.stack.imgur.com/cLqZB.png


Code

Here is the constructor to my code. The label does not show up if the buttons are visible.

        public Grid()
        {
            super();
            setLayout(null);
            setBounds(125,205,290,290);
            setBackground(new Color(139,69,19));
            setBorder(new LineBorder(Color.black,5));

            for(int a = 0; a < piece.length; a ++)
            {
                for(int b = 0; b < piece[0].length; b ++)
                {
                    piece[a][b] = new DiceButton(0,0,a,b,null);
                    piece[a][b].addActionListener(this);
                    add(piece[a][b]);
                }
            }

            scoringVisual = new JLabel("+ 200");
            scoringVisual.setBounds(110, 135, 70, 30);
            scoringVisual.setFont(new Font("Arial Rounded MT Bold", Font.BOLD, 20));
            scoringVisual.setOpaque(true);
            scoringVisual.setBackground(new Color(0,87,0));
            scoringVisual.setForeground(new Color(38,224,2));
            scoringVisual.setHorizontalAlignment(JLabel.CENTER);
            scoringVisual.setBorder(new LineBorder(Color.black,1));
            add(scoringVisual);
        }
Was it helpful?

Solution

In your last posting I stated:

Basically the last component added is painted first.

However, I then posted example code (which was the same as your code):

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

Of course I meant to post:

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

Of course this is still a terrible way to do what your want. You should NOT be using a null layout. You should not be using setBounds() to position your components on the panel.

I don't have a background with glasspanes or anything,

That is why I gave you the link to the tutorial. It contains working exmaples.

but I wish to do this in the easiest way possible.

That is why I gave you the link to the tutorial. Sometimes you need to learn the basics to take advantage of what Swing has to offer. Since you don't know how Swing works you don't know that drawbacks of your current approach. We are trying to point you in the right direction at the start of your design phase so you don't have to revisit the design in the future when you encounter problems and it will become harder to change.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top