Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding label over multiple labels in java

Tags:

java

swing

I have added multiple labels (boxes) on JFrame in the form of a grid. Now I want to add a label (ladder) over some of the labels in the grid, for this I am doing something like this:

for(int i=0, x=0; i<10; i++,x+=50) {
    for(int j=0, y=0; j<10; j++,y+=50) {
        box[i][j] = new JLabel(j);
        box[i][j].setOpaque(true);
        box[i][j].setBackground(Color.BLACK);   
        box[i][j].setBounds(x, y, 50,50);
        board.add(box[i][j]);
    }
}

ladder.setBounds(0, 0, 50, 200);
ladder.setOpaque(true);
board.add(ladder);

But this code does not adds ladder over boxes. So kindly tell how can I add ladder label over boxes.

like image 229
Sajal Ali Avatar asked Jul 28 '26 10:07

Sajal Ali


1 Answers

You may use the JLayeredPane from your JFrame to achieve this.

Just put the board on the back layer, and the ladder on the front layer.

Here is an example, close to your actual code :

    JFrame frame = new JFrame();

    JPanel board = new JPanel();

    board.setLayout(null);
    board.setBounds(0, 0, 500, 500);

    for (int i = 0, x = 0; i < 10; i++, x += 50) {
        for (int j = 0, y = 0; j < 10; j++, y += 50) {
            JLabel lab = new JLabel("" + j);
            lab.setOpaque(true);
            lab.setBackground(Color.BLACK);
            lab.setBounds(x, y, 50, 50);
            board.add(lab);
        }
    }

    JLabel ladder = new JLabel();
    ladder.setBackground(Color.RED);
    ladder.setBounds(0, 0, 50, 200);
    ladder.setOpaque(true);

    JLayeredPane pane = frame.getLayeredPane();

    pane.add(ladder, new Integer(2)); // front
    pane.add(board, new Integer(1));  // back

    frame.setVisible(true);

Some more information here : How to Use Layered Panes

like image 192
Arnaud Avatar answered Jul 30 '26 00:07

Arnaud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!