所以我在這裏有一小段代碼。什麼代碼是應該做的:加速不會加上
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
@SuppressWarnings("serial")
public class squareMovingUsingArrowKeys extends JPanel implements ActionListener,KeyListener {
static int x;
static int y;
static double acceleration=0.3;
static int originSpeed;
static int actualSpeed;
static boolean a=false;
Timer timer;
squareMovingUsingArrowKeys() {
x = 0;
y = 0;
acceleration = 0.3;
actualSpeed = 1;
}
@SuppressWarnings("deprecation")
public void keyPressed(KeyEvent e) {
a = true;
System.out.println(actualSpeed);
actualSpeed+=acceleration;
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
x -= actualSpeed;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
x += actualSpeed;
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
y -= actualSpeed;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
y += actualSpeed;
}
//first call move to update x and y and later repaint that JPanel
move(x, y);
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(125,125,255));
g.fillRect(x, y, 20, 20);
g.setColor(new Color(100,255,100));
g.fillOval(x, y, 20, 20);
if(x>=500){
x=500;
}else if(y>=500){
y=500;
}else if(x<=0){
x=0;
}else if(y<=0){
y=0;
}
}
public void start() {
keyPressed(null);
paintComponent(null);
}
public static void main(String[] args) {
JFrame f = new JFrame("Moving");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
squareMovingUsingArrowKeys m = new squareMovingUsingArrowKeys();
f.add(m);
f.setSize(500, 500);
f.setVisible(true);
f.addKeyListener(m);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
originSpeed = 1;
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
- 能夠「加快」爲你按住一個按鈕
停止當x或y是在500
移動次要方向
但顯然,它不起作用。
我該如何解決這個問題?
停下來是什麼意思?停止加速?你是什麼意思的次要方向? – Sneh
完全停止,次要方向是對角線方向。 – bleh
什麼意思是「不起作用」?不工作表現本身如何? – sisyphus