我比初学者对Java的理解要好一点,而且我在学生作业方面遇到了麻烦。我不得不把一个类(student.java)“变成一个按钮” - 我已经完成了(这就是为什么不是创建一个新的JButton实例,我的代码创建了一个新的“student”实例)。我需要让按钮将其位置重新定位到用户单击鼠标的位置。我已成功完成了这项工作,因此我的任务要求已得到满足 但是,我想让按钮平滑移动到鼠标点击的位置,而不是突然从前一个位置跳到新位置。以下是我的代码。 mouseClicked()方法内部的数学是我尝试过的,但它对按钮的运动没有影响。
任何提示将不胜感激。谢谢!
public myJPanel(){
super();
setLayout(null);
setBackground(Color.decode("#F5F2EB"));
setVisible(true);
setPreferredSize(new Dimension(640,480));
setMinimumSize(new Dimension(640,480));
setMaximumSize(new Dimension(640,480));
Font f = new Font("Copperplate Gothic Bold", Font.BOLD, 16);
student btn = new student("First","Last", num, "");
add(btn);
btn.setBounds(100, 150, 400, 90);
btn.setText(btn.getInfo());
btn.setBackground(Color.decode("#89A690"));
btn.setForeground(Color.decode("#F5F2EB"));
btn.setOpaque(true);
btn.setFont(f);
btn.setBorder(BorderFactory.createEmptyBorder(20, 40, 20, 40));
// move btn object
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int x = e.getX(); //mouse click x position
int y = e.getY(); //mouse click y position
int px = btn.getX() - x; //previous btn x position(to get distance between old / new position)
int py = btn.getY() - y; //previous btn y position(to get distance between old / new position)
double speed = 5; //speed
double ang = (float)Math.atan2(py, px) * 180 / Math.PI; //angle
x += Math.cos(ang * Math.PI/180) * speed; //move to x
y += Math.sin(ang * Math.PI/180) * speed; //move to y
btn.setLocation(x,y); //relocate button to new location
}});
答案 0 :(得分:3)
您的代码中需要某种动画概念,只需更新位置就不会顺利移动它。您需要的更改
实施例。在这里,我计算了总距离,然后根据时间和速度插入“距离到目前为止”。
另请注意使用Math.toDegrees()和Math.toRadians(),尽管你根本不需要它们,除非你想在其他地方使用ang作为度数......
public class Foo {
private static class Animate extends JPanel {
private JButton btn;
private int startX;
private int startY;
private long startTime;
private double ang;
private double distance;
public Animate() {
super();
setLayout(null);
btn = new JButton("Dr Horse");
btn.setBounds(100, 150, 40, 10);
add(btn);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
startX = btn.getX();
startY = btn.getY();
startTime = System.nanoTime();
int px = btn.getX() - e.getX();
int py = btn.getY() - e.getY();
distance = Math.sqrt(px * px + py * py);
ang = Math.toDegrees(Math.atan2(py, px));
}
});
Timer timer = new Timer(1000 / 20, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double duration = (System.nanoTime() - startTime) / 1e6;
int speed = 50;// pixels per second
double distanceSoFar = Math.min(speed * duration / 1000d, distance);
int x = startX - (int) (distanceSoFar * Math.cos(Math.toRadians(ang)));
int y = startY - (int) (distanceSoFar * Math.sin(Math.toRadians(ang)));
btn.setLocation(x, y);
}
});
timer.setRepeats(true);
timer.start();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new Animate());
frame.setSize(500, 400);
frame.setVisible(true);
}
}