我有一个基本程序,您可以在其中使用箭头键绕一圈移动。我正在尝试使球无法进入某个区域(蓝色矩形),但它不起作用。我正在使用 Eclipse。
package TLOT;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Movement extends JPanel implements ActionListener, KeyListener
{
Timer tm = new Timer(5,this);
int x = 0, velX = 0;
int y = 0, velY = 0;
public Movement()
{
tm.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void actionPerformed(ActionEvent e)
{
if (x < 0){
velX = 0;
x = 0;
}
if (x > 633){
velX = 0;
x = 533;
}
if (y < 0){
velY = 0;
y = 0;
}
if (y > 410){
velY = 0;
y = 310;
}
//this is that part thats supposed to make it stop if it hits a certain point.
if (50 < x && x < 100 && y > 50 && y > 100){
velX = 0; //700 , 500
velY = 0;
}
x = x + velX;
y = y + velY;
repaint();
}
public void keyPressed(KeyEvent e){
int c = e.getKeyCode();
if (c == KeyEvent.VK_LEFT || c == KeyEvent.VK_A){
velX = -1;
velY = 0;
}
if (c == KeyEvent.VK_UP || c == KeyEvent.VK_W){
velX = 0;
velY = -1;
}
if (c == KeyEvent.VK_RIGHT || c == KeyEvent.VK_D){
velX = 1;
velY = 0;
}
if (c == KeyEvent.VK_DOWN || c == KeyEvent.VK_S){
velX = 0;
velY = 1;
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){
velX = 0;
velY = 0;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.fillOval(x, y, 50, 50);
g.setColor(Color.blue);
g.fillRect(320, 200, 40, 60);
tm.start();
}
public static void main(String[] args) {
Movement q = new Movement();
JFrame jf = new JFrame();
jf.setTitle("Movement Test");
jf.setSize(700,500);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(q);
jf.setVisible(true);
}
}