我试图开发一款2球拍游戏。我创建了2个矩形(作为球拍)。 我尝试从键盘控制它们并使用 KeyListener 事件处理程序为此目的...当我运行我的程序有时它工作,有时不。 我想知道为什么它有效,但没有其他。 这是我的代码。 请告诉我哪里弄错了? 感谢
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test implements KeyListener, ActionListener {
JFrame f;
MyPanel p; // Instance of MyPanel for left and right rackets
BallPanel bp; // Instance of BallPanel for Bouisng ball
int x1, y1, x2, y2;
int x, y;
public Test(){
f = new JFrame("2 Rackets Game");
Container c = f.getContentPane();
c.setLayout(new BorderLayout());
x = 5; y = 10;
p = new MyPanel();
bp = new BallPanel();
c.add(bp);
c.add(p);
f.setSize(600, 400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p.addKeyListener(this);
p.setFocusable(true);
Timer t = new Timer(5, this);
t.start();
}
public void keyTyped(KeyEvent e) {/*_______*/}
int speed = 30;
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_W){
p.mY1 -= speed;
}
if(e.getKeyCode() == KeyEvent.VK_S){
p.mY1 += speed;
}
if(e.getKeyCode() == KeyEvent.VK_UP){
p.mY2 -= speed;
}
if(e.getKeyCode() == KeyEvent.VK_DOWN){
p.mY2 += speed;
}
p.repaint();
}
public void keyReleased(KeyEvent e) {/*_______*/}
public void actionPerformed(ActionEvent e){
if (f.getWidth()-25 == bp.mX){
x = -5;
}
if (f.getHeight()-50 == bp.mY){
y = -2;
}
if(bp.mX == 0){
x = 5;
}
if(bp.mY == 0){
y = 2;
}
bp.mX += x;
bp.mY += y;
bp.repaint();
}
public static void main(String arg[]){
Test t = new Test();
}
Alos这里是“MyPanel”类的代码(用于在屏幕上绘制矩形)
import javax.swing.*;
import java.awt.*;
public class MyPanel extends JPanel {
// variables used to draw rectangles at different locations
int mX1 = 20;
int mY1 = 120;
int mX2 = 560;
int mY2 = 120;
// overriding paintComponent method
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.BLUE);
// Left Racket
g2.fillRect(mX1, mY1, 5, 80);
//Right Racket
g2.fillRect(mX2, mY2, 5, 80);
}
}