我想制作一个GUI程序,当我按下鼠标按钮时,将标签移动到按下的X和Y位置。我这样做是很容易的,但是我现在想像是缓慢移动的效果。我尝试使用thread.sleep()来执行此操作,但没有成功。您可以提供意见或代码帮助我吗?这是我的代码:

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

        }
    });
}

}


这是我使用的图像:

最佳答案

写作是乐趣的一半...


startPointnextStep存储为Points
初始化javax.swing.Timer
用户单击时,保存根startPoint,将nextStep设置为鼠标位置,然后调用timer.start()
Timer.actionPerformed()在返回到nextStep时需要计算startPoint点。
如果startPoint等于nextStep调用timer.stop()

10-06 15:00