因此,我在学习 Java 时一直在编写一个简单的程序,该程序会显示一个小矩形屏幕,上面有一个圆圈在移动。背景和圆圈也会改变颜色和速度。
现在我正在尝试添加 KeyEvents,这样当用户键入一个字符时,圆圈会改变方向。几个小时以来,我一直在尝试处理 KeyEvent 功能,但我被卡住了。
您将如何更改以下代码以使程序响应键盘输入:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.JFrame;
public class MovingCircle3 extends JFrame implements ActionListener {
Ellipse2D.Double myEllipse;
Rectangle2D.Double backgroundRectangle;
private int paintTally = 0; // Counts # of repaints.
private int timerSpeed = 500; // Holds speed of timer. Initially: 500ms.
private Timer timerOjbect;
private char shapeMoveInput = 'd';
public MovingCircle3() {
myEllipse = new Ellipse2D.Double(30, 30, 20, 20); // Ellipse starting point
backgroundRectangle = new Rectangle2D.Double(0, 0, 400, 300); // Background.
this.timerOjbect = new Timer(500, this);
timerOjbect.start(); //Creates and starts timer.
}
public static void main(String[] args) {
System.out.print("Game Controls: \n l = Move left. \n r = Move right. \n u = Move up. \n d = Move down. \n ENTER COMMAND: "); // Game controls.
MovingCircle3 b = new MovingCircle3();
b.setVisible(true);
b.setSize(400, 300);
b.setVisible(true);
b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void keyPressed(KeyEvent e) {
try {
shapeMoveInput = e.getKeyChar();
} catch (Exception ex) {
shapeMoveInput = 'd';
}
}
public void actionPerformed(ActionEvent ae) {
//This will be called by the Timer
if (shapeMoveInput == 'l') {
myEllipse.setFrame(myEllipse.getX() - 1, myEllipse.getY(), myEllipse.getWidth(), myEllipse.getHeight()); //Move 1 x-pixel left
} else if (shapeMoveInput == 'r') {
myEllipse.setFrame(myEllipse.getX() + 1, myEllipse.getY(), myEllipse.getWidth(), myEllipse.getHeight()); //Move 1 x-pixel right
} else if (shapeMoveInput == 'u') {
myEllipse.setFrame(myEllipse.getX(), myEllipse.getY() - 1, myEllipse.getWidth(), myEllipse.getHeight()); //Move 1 y-pixel up
} else if (shapeMoveInput == 'd') {
myEllipse.setFrame(myEllipse.getX(), myEllipse.getY() + 1, myEllipse.getWidth(), myEllipse.getHeight()); //Move 1 y-pixel
}
repaint();
}
public void paint(Graphics g) {
paintTally++; // Increments by one for every repaint().
if (paintTally % 25 == 0) { // Take modulus 25 of paintTally to execute every 25 paints.
timerSpeed = (int) (timerSpeed / 2);
timerOjbect.setDelay(timerSpeed); // Divide speed by 2 and see to timer length.
}
int isPaintTen = (int) (paintTally / 10); // Divide current count by 10.
Graphics2D g2 = (Graphics2D) g;
if ((isPaintTen % 2) == 0) { // Take modulus to set if #/10 is odd or even.
g2.setColor(Color.YELLOW);
g2.fill(backgroundRectangle);
g2.setColor(Color.RED);
g2.draw(myEllipse);
} else if ((isPaintTen % 2) == 1) {
g2.setColor(Color.RED);
g2.fill(backgroundRectangle);
g2.setColor(Color.YELLOW);
g2.draw(myEllipse);
}
}
}