gpt4 book ai didi

java - 将 JLabel 添加到 JPanel 会扰乱其中的项目

转载 作者:行者123 更新时间:2023-12-02 13:07:24 24 4
gpt4 key购买 nike

我正在尝试创建一个简单的平台游戏,并且正在尝试将角色放入 JPanel 上。我遇到了一个问题。如果不移动已放置的图 block (草地、天空等),我无法将角色添加到 JPanel(请注意,该角色采用包含图像图标的 JLabel 形式)。

我用来放置 block 的代码是:

static void drawScreen() throws IOException {
panel.removeAll();
int tile = 0;
int line = 0;
for (int i = 0; i < t.length; i++, tile++) {
boolean tD = tile % 32 == 0;
if (tD) {
tile = 0;
line++;
}
if (t[i] == 0) {
File f = new File(sPath);
BufferedImage s = ImageIO.read(f);
JLabel l = new JLabel(new ImageIcon(s));
c.gridx = tile;
c.gridy = line;
c.insets = new Insets(0, 0, 0, 0);
panel.add(l, c);
}
if (t[i] == 1) {
File f = new File(gPath);
BufferedImage g = ImageIO.read(f);
JLabel l = new JLabel(new ImageIcon(g));
c.gridx = tile;
c.gridy = line;
c.insets = new Insets(0, 0, 0, 0);
panel.add(l, c);
}
if (t[i] == 2) {
File f = new File(dPath);
BufferedImage d = ImageIO.read(f);
JLabel l = new JLabel(new ImageIcon(d));
c.gridx = tile;
c.gridy = line;
c.insets = new Insets(0, 0, 0, 0);
panel.add(l, c);
}
}

frame.revalidate();
frame.repaint();
}

数组 t 包含所有图 block ID。它包含 672 个整数,其中大部分为 0。

谁能告诉我如何在特定坐标处添加角色而不移动其他图 block 。

我目前添加它的方式是:

static void addChar() throws IOException {

File f = new File(cPath);
BufferedImage c1 = ImageIO.read(f);
BufferedImage c = runResize(c1, 50, 76);

JLabel l = new JLabel(new ImageIcon(c));
l.setOpaque(false);
panel.add(l);

frame.revalidate();
frame.repaint();
}

当我运行它时,它输出如下:(请原谅我的糟糕艺术)

输出图像:

/image/sXKo1.png

如果您有任何疑问,请告诉我。

最佳答案

I can't add the character to the JPanel (Note that the character is in the form of a JLabel containing an imageicon) without moving the, already placed, tiles (the grass, the sky, ect.).

如果您要使用真实组件来表示面板上的草地、天空,那么您不能向该面板添加更多组件。

您可以尝试使用 JLayeredPane。这将允许您在彼此之上绘制多个组件。因此,一层将包含带有草和天空的面板。下一层将包含您要添加的“字符”。请阅读 Swing 教程中有关如何使用 LayeredPanes 的部分,以获取更多信息和示例。

另一个选项是自定义面板的 paintComponent() 方法,以使用图像“绘制”草地和天空。然后,您可以将“字符”组件添加到面板中,因为它现在将是面板上唯一的组件。这可能是更好的方法。

关于java - 将 JLabel 添加到 JPanel 会扰乱其中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44090589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com