将JLabel / ImageIcon放在另一个JLabel / ImageIcon之上

时间:2017-05-20 19:00:00

标签: java imageicon

我正在尝试创建自己的小平台游戏,我遇到的问题是将角色放到屏幕上。如何加载背景是通过使用BufferedImages将png放到屏幕上。我将BufferedImages转换为ImageIcons并添加到屏幕。 像这样:

File f = new File("Path Of File");
BufferedImage d = ImageIO.read(f);
JLabel l = new JLabel(new ImageIcon(d));
c.gridx = tile; // Tile is set to the corresponding position on an int array
c.gridy = line; // ^^ So is line
c.insets = new Insets(0, 0, 0, 0);
panel.add(l, c);

我想要做的是将角色的图像设置在其中一个图块的顶部。 以下是我想要开展工作的一个例子:

File f = new File(cPath);
    BufferedImage c1 = ImageIO.read(f);
    JLabel l = new JLabel(new ImageIcon(c1));
    l.setLocation(x, y);
    p2.add(l);`

p2是JPanel。布局设置为null:

p2.setLayout(null);

面板是JPanel。 GridBagLayout创建时的布局是:

JPanel panel = new JPanel(new GridBagLayout());

两个面板都添加到JFrame中,如下所示:

frame.getContentPane().add(panel, BorderLayout.NORTH);
frame.getContentPane().add(p2);

因此,如果有人能让我知道如何将JLabel / ImageIcon放在另一个JLabel / ImageIcon之上,我们将不胜感激。

编辑:如果您对我想要实现的目标有任何疑问,请告诉我。

1 个答案:

答案 0 :(得分:0)

默认情况下,组件的大小为(0,0)。

因此,如果使用空布局,则负责设置添加到父标签的每个标签的大小。

所以基本逻辑是:

JLabel child = new JLabel( new ImageIcon() );
child.setSize( child.getPreferredSize() );
child.setLocation(...);
JLabel parent = new JLabel( new ImageIcon(...) );
parent.add( child );
frame.add( parent );

或另一种选择是使用布局管理器。例如,您可以使用以下内容将孩子置于父母的中心:

parent.setLayout( new GridBagLayout() );
parent.add(child, new GridBagConstraints());

现在没有必要使用子项的大小/位置,因为布局管理器会照顾它。

相关问题