我一直在大学学习Java,我很新,但我正在努力提高。我正在尝试设置一个显示草地图块网格的 GUI(使用带有草地图标的 JLabels(,但我想在草地上添加一些其他图标(角色图标(,以便我可以看到一个角色站在草地上。我想我可以通过使用 JLayeredPane 并在同一位置添加另一个 JLabel 但具有更高的层优先级来做到这一点,但它似乎不起作用。关于我应该怎么做的任何建议?
谢谢:)
编辑:我设法使用MigLayout和setOpaque(false(指令来做到这一点。感谢您的回答:)
这是我用来解决这个问题的代码片段。
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 457, 330);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLayeredPane panel = new JLayeredPane();
panel.setBounds(0, 0, 457, 330);
frame.getContentPane().add(panel);
panel.setLayout(null);
JPanel background = new JPanel();
background.setBounds(0, 0, 457, 330);
panel.add(background);
background.setLayout(new MigLayout("","",""));
//In my particular problem I used some constraints, but they're not needed
backgroundLabels = new JLabel[NCOLS][NROWS];
for (int i = 0; i < NCOLS; i++)
for (int j = 0; j < NROWS; j++) {
backgroundLabels[i][j] = new JLabel(backgroundIcon);
//Assuming you have a backgroundIcon variable where you saved your icon
background.add(backgroundLabels[i][j], "cell " + i + " " + j);
}
JPanel characterPanel = new JPanel();
panel.setLayer(characterPanel, 1);
characterPanel.setBounds(0, 0, 457, 330);
panel.add(characterPanel);
characterPanel.setOpaque(false);
characterPanel.setLayout(new MigLayout("","",""));
characterLabels = new JLabel[NCOLS][NROWS];
for (int i = 0; i < NCOLS; i++)
for (int j = 0; j < NROWS; j++) {
characterLabels[i][j] = new JLabel("");
//Creates empty character labels. You can then add icons using setIcon()
characterPanel.add(characterLabels[i][j], "cell " + i + " " + j);
}
}