简体   繁体   English

如何在Java中移动图片?

[英]How to move Image in Java?

I am beginner to Swing and I am writing some codes. 我是Swing的初学者,正在编写一些代码。 I have added images on JLabel and JLabel on JFrame . 我在JLabelJFrame JLabel上添加了图像。 I want to move that Image. 我想移动该图像。 Is it possible to move that image(fish). 是否可以移动该图像(鱼)。 If yes, How can I do it? 如果是,我该怎么办?

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

    public class Aquarium extends JFrame{

    private ImageIcon fish2image;
    private ImageIcon fish1image;
    private ImageIcon image;
    private JLabel imglabel;
    private JLabel fish1label;
    private JLabel fish2label;
    int numberFish = 12;

    public Aquarium(){
        initComponents();
        setTitle("The Aquarium");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setResizable(false);
        setBounds(500,200,500,300); //left,top,width,height      

        add(fish1label);
        add(fish2label);
        add(imglabel);

    }
    private void initComponents(){

        image = new ImageIcon(getClass().getResource("../res/aquarium.gif"));
        fish1image = new ImageIcon(getClass().getResource("../res/smallFish.gif"));
        fish2image = new ImageIcon(getClass().getResource("../res/smallFish2.gif"));
        imglabel = new JLabel(image);
        fish1label = new JLabel(fish1image);
        fish2label = new JLabel(fish2image);
        fish1label.setBounds(100,100,250,200);
        fish2label.setBounds(50,25,200,200);
    }

    public static void main(String[] args) {
        new Aquarium();
    }
}

Repeat question. 重复问题。 But you would shift the x, and y values (Based on keyBindings or KeyListener added on frame) and it will automatically repaint. 但是您需要移动x和y值(基于在框架上添加的keyBindings或KeyListener),它将自动重新绘制。

But since you want the fist to move automatically. 但是,既然您希望拳头自动移动。 You are going to need either a loop based on a swing timer, Thread.sleep(1000); 您将需要一个基于摆动计时器的循环Thread.sleep(1000); <= Highly not recommended, or a Thread. <=强烈建议不要使用Thread。

Then you would shift the x and y values as described above as a certain amount of seconds pass within the method that you choose 然后,您将在选择的方法内经过一定的秒数后,如上所述移动x和y值

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

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