java 摆动中的绝对定位图像图标

Absolute Positioning Image Icons in java swing

所以我正在尝试为我的项目编写本质上是使用 java swing 在 3 种不同的神奇宝贝之间进行的神奇宝贝战斗。然而,让我停滞不前的部分是动画。我尝试使用带有 setLocation 的空布局,以便我可以根据计时器移动图像图标,但问题是,您可能知道,图像图标不会显示在空布局中。无论如何要改变它,以便它以这种方式工作。 这就是我声明我的照片的方式

java.net.URL torterraPic = getClass().getResource("torterra-1.gif");

ImageIcon torterra = new ImageIcon(new ImageIcon(torterraPic).getImage().getScaledInstance(100, 100, Image.SCALE_DEFAULT));

然后我将我的图像图标放在我添加到框架的 JLabel 中,然后我执行 setLocation 以选择它的位置。

我知道不鼓励使用绝对定位,但我觉得这是最好的方法(假设可以添加图片),因为那样我可以操纵 setLocation 使其向上移动在攻击过程中。我尝试过使用 gridbag 和 grid layout 来尝试做到这一点,但对我来说都不方便。

所以,如果有什么方法可以进行此锻炼,请告诉我。 提前致谢!

I tried using a null layout with setLocation so that I can move the imageicons based on a timer but the issue is, as you probably know, the imageicons won't show up in the null layout.

是的,他们会,但您现在负责执行布局管理器功能,这意味着您需要设置标签的位置和 size

通常你会做这样的事情:

label.setIcon(...);
label.setSize( label.getPreferredSize() ):
label.setLocation(...);

然后在您的动画中,您只需根据需要更改位置。

无需使用 null 布局和组件绝对定位,因为您的图像精灵不应该是 JLabel 或其他组件,而是创建 BufferedImage 精灵,然后按照绘画教程在单个绘图中绘制 JPanel 的 paintComponent 方法 -- Lesson: Performing Custom Painting.

先在静态位置绘制背景图像,然后通过 g.drawImage(...) 覆盖的 x 和 y 参数移动精灵的位置。通过使用 ActionListener 的 Swing 计时器或通过其他侦听器(例如键绑定)来驱动动画。

JLabel label=new JLabel("");
    Image img=new ImageIcon(this.getClass().getResource("hancie.png")).getImage();
    label.setIcon(new ImageIcon(img));
    label.setBounds(10,50,200,200);
    label.setBorder(new LineBorder(Color.BLACK,4));
    frame.add(label);