简体   繁体   English

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

[英]Placing an JLabel/ImageIcon on top of another JLabel/ImageIcon

I am trying to create my own small platformer and the problem I am having is putting the character onto the screen. 我正在尝试创建自己的小型平台游戏,而我遇到的问题是将角色放置在屏幕上。 How I have the background loaded on is by using BufferedImages to put a png onto the screen. 我如何加载背景是通过使用BufferedImages将png放置到屏幕上。 I convert the BufferedImages to ImageIcons and add to the screen. 我将BufferedImages转换为ImageIcons并添加到屏幕。 Like this: 像这样:

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);

And what I am trying to do, is set the image of the character on top of one of those tiles. 而我想做的是将角色的图像设置在这些图块之一的顶部。 Here is an example of what I am trying to get to work: 这是我要开始工作的示例:

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 is a JPanel. p2是一个JPanel。 The layout was set to null: 布局设置为null:

p2.setLayout(null);

panel is a JPanel. 面板是一个JPanel。 The layout was to to GridBagLayout when it was created: 布局是在创建时到GridBagLayout的:

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

Both panels were added to the JFrame like so: 这两个面板都添加到了JFrame中,如下所示:

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

So if anyone could let me know how to put the JLabel/ImageIcon on top of another JLabel/ImageIcon, it would be greatly appreciated. 因此,如果有人能让我知道如何将JLabel / ImageIcon放在另一个JLabel / ImageIcon之上,将不胜感激。

EDIT: If you have any questions about what I am trying to achieve, please let me know. 编辑:如果您对我要达到的目标有任何疑问,请告诉我。

By default components have a size of (0, 0). 默认情况下,组件的大小为(0,0)。

So if you use a null layout you are responsible for setting the size of each label you add to the parent label. 因此,如果使用空布局,则负责设置添加到父标签的每个标签的大小。

So the basic logic is: 因此,基本逻辑是:

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

Or another option is to use layout managers. 另一个选择是使用布局管理器。 For example you can center the child on the parent using: 例如,您可以使用以下方法将孩子放在父母的中心:

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

Now there is no need to play with the size/location of the child since the layout manager will look after this. 现在,无需处理子项的大小/位置,因为布局管理器将负责此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM