简体   繁体   English

如何缓慢地(像效果一样)移动标签(图像)以摆动鼠标在JAVA中的位置

[英]How to slowly(like a effect) move a label(image) to click position of mouse in JAVA with swing

I want to make a GUI program that, when I press mouse button, moves label to the position of pressed X and Y locations. 我想制作一个GUI程序,当我按下鼠标按钮时,将标签移动到按下的X和Y位置。 I did that, it was easy, but I want to make it now like a slow moving effect. 我这样做是很容易的,但是我现在想像是缓慢移动的效果。 I tried to do it with thread.sleep() but it didn't work. 我试图用thread.sleep()来做,但是没有用。 Can you help me with ideas or code? 您可以提供意见或代码帮助我吗? This is my code: 这是我的代码:

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class jGame extends JFrame {

private JPanel contentPane;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                jGame frame = new jGame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public jGame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 568, 459);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(new BorderLayout(0, 0));

    JPanel panel = new JPanel();
    contentPane.add(panel, BorderLayout.CENTER);

    JLabel robot = new JLabel("");
    robot.setIcon(new ImageIcon("/home/ubuntu/Desktop/robot.png"));
    panel.add(robot);
    panel.addMouseListener(new MouseListener() {

        @Override
        public void mouseClicked(MouseEvent e) {
            robot.setLocation(e.getX() - 25, e.getY() - 40);
        }

        @Override
        public void mouseReleased(MouseEvent e) {

        }

        @Override
        public void mousePressed(MouseEvent e) {

        }

        @Override
        public void mouseExited(MouseEvent e) {

        }

        @Override
        public void mouseEntered(MouseEvent e) {

        }
    });
}

}

And here is the image I use: 这是我使用的图像:
机器人

Writing is half the fun... 写作是乐趣的一半...

  1. Store the startPoint & nextStep as Points startPointnextStep存储为Points
  2. Initialize a javax.swing.Timer 初始化javax.swing.Timer
  3. When user clicks, save the Root startPoint , set nextStep to mouse location and call timer.start() . 当用户点击,保存根startPoint ,设置nextStep鼠标的位置,并呼吁timer.start()
  4. Timer.actionPerformed() needs to calculate the nextStep Point as it moves back to startPoint . Timer.actionPerformed()需要计算nextStep点,因为它移回startPoint
  5. if startPoint equals nextStep call timer.stop() 如果startPoint等于nextStep调用timer.stop()

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

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