我以网格的形式在 JFrame 上添加了多个标签(框)。现在我想在网格中的一些标签上添加一个标签(梯子),为此我正在做这样的事情:
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);
但是这段代码没有在盒子上添加梯子。所以请告诉我如何在盒子上添加梯形标签。
最佳答案
您可以使用 JFrame
中的 JLayeredPane 来实现此目的。
只需将板放在后层,将梯子放在前层。
这是一个示例,接近您的实际代码:
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);
这里有更多信息:How to Use Layered Panes
关于java - 在java中的多个标签上添加标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36335195/