我在大学里一直在学习Java,我很新,但我努力改进。 我试图设置一个显示Grass Tiles网格的GUI(使用JLabel with Grass图标),但我想在草顶上添加一些其他图标(Character icons)以便我可以看到一个角色站在草地上。我认为我可以通过使用JLayeredPane并在同一位置添加另一个JLabel但具有更高的图层优先级,但它似乎无法工作。关于我应该做什么的任何建议?
谢谢:)
编辑:我设法使用MigLayout和setOpaque(false)指令执行此操作。谢谢你的回答:)
答案 0 :(得分:0)
这是我用来解决这个问题的代码片段。
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);
}
}