Swing 在另一个JLabel上添加带有透明背景图标的JLabel并同时显示
我一直在我的大学学习Java,我是个新手,但我正在努力提高。 我正在尝试设置一个GUI来显示草块网格(使用带有草图标的JLabel),但我想在草的顶部添加一些其他图标(角色图标),以便我可以看到一个角色站在草上。我想我可以通过使用JLayeredPane并在同一位置添加另一个JLabel来实现这一点,但是具有更高的层优先级,但是它似乎不起作用。我该怎么做有什么建议吗 谢谢:)Swing 在另一个JLabel上添加带有透明背景图标的JLabel并同时显示,swing,user-interface,icons,jlabel,jlayeredpane,Swing,User Interface,Icons,Jlabel,Jlayeredpane,我一直在我的大学学习Java,我是个新手,但我正在努力提高。 我正在尝试设置一个GUI来显示草块网格(使用带有草图标的JLabel),但我想在草的顶部添加一些其他图标(角色图标),以便我可以看到一个角色站在草上。我想我可以通过使用JLayeredPane并在同一位置添加另一个JLabel来实现这一点,但是具有更高的层优先级,但是它似乎不起作用。我该怎么做有什么建议吗 谢谢:) 编辑:我使用miglayet和setOpaque(false)指令成功地做到了这一点。谢谢你的回答:)这是我用来解决这个
编辑:我使用miglayet和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);
}
}
private void initialize(){
frame=新的JFrame();
框架.立根(100100457330);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLayeredPane panel=新的JLayeredPane();
面板.立根(0,0,457,330);
frame.getContentPane().add(面板);
panel.setLayout(空);
JPanel background=新的JPanel();
背景:立根(0,0457330);
面板。添加(背景);
setLayout(新的MigLayout(“,”,”);
//在我的特殊问题中,我使用了一些约束,但它们不是必需的
背景标签=新的JLabel[ncol][NROWS];
对于(int i=0;i
有很多方法可以做到这一点。您可以将布局管理器应用于草地标签,以便向其添加组件,这样您可以使用GridLayout
仅用于显示草地平铺,也可以使用草地图像制作自定义组件绘制背景,再次向其添加布局管理器,以便添加组件。两者都有优点,自定义面板更复杂,但可以让您更好地控制组件的大小,标签更简单,但只会是图标的大小,而不是内容如果标签是图标的大小就好了。如果您有时间,可以发布一个示例代码吗?请在您的问题中添加一个答案(包括a形式的代码),而不是用“我解决了这个问题…”来编辑您的问题,这样将来看到这个问题的任何人都知道如果他们遇到类似的问题或问题,该如何处理@MadProgrammer没有为此发布示例代码,因为您没有发布可使用的代码,但这里有一些和setLayout(null)
和setBounds()
是不好的做法,您将null layout
与之混合,请仅与布局管理器联系。阅读并用英语写出答案