我想用计时器提供射弹动作。首先,我创建计时器,然后用计时器更改x和y的位置。当我检查所有X和Y点都已更新但我无法重新绘制新的X和Y.如何重新绘制我的面板并提供抛射物运动?提前致谢。这是我的代码。
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Deneme extends JPanel {
double positionY = 100;
double positionX = 100;
double velocityY = 20;
double velocityX = 20;
double acceleration = -10;
Timer timer;
public Deneme() {
timer = new Timer(100, new myTimerListener());
}
private class myTimerListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
update(0.09);
repaint();
}
}
void update(double dt) {
positionX += velocityX * dt;
positionY += velocityY * dt + acceleration * 0.5 * dt * dt;
velocityY += acceleration * dt;
System.out.println(positionX + " " + positionY);
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawOval((int) positionX, (int) positionY, 15, 15);
}
public double positionY() {
return positionY;
}
public double velocityY() {
return velocityY;
}
public double positionX() {
return positionX;
}
public double velocityX() {
return velocityX;
}
public static void main(String[] args) {
new Deneme().timer.start();
JFrame frame = new JFrame("Basketball");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1500, 1000);
frame.add(new Deneme());
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
}