我一直在学习如何在Java中使用rpg风格的游戏,并找到了不错的教程。但是,本教程显示了如何使用键侦听器移动精灵,我想做的是通过在屏幕上获取鼠标位置来移动精灵,并在没有任何键侦听器的情况下自行移动精灵。这是我到目前为止的代码,谢谢您的帮助! (哦,问题在于精灵没有移动,忘了说...是因为move方法中的while循环吗?)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Image;
import java.awt.event.*;
import javax.swing.ImageIcon;
public class SpaceCraft {
private String craft = "craft.png";
private int dx;
private int dy;
private int x;
private int y;
private Image image;
public SpaceCraft() {
ImageIcon spaceCraft = new ImageIcon(this.getClass().getResource(craft));
image = spaceCraft.getImage();
x = 40;
y = 60;
}
public void move() {
while ((x==Board.mouseX)==false) {
if (x < Board.mouseX){
x += 1;
} else if (x > Board.mouseX){
x -= 1;
}
}
while ((y==Board.mouseY)==false) {
if (y < Board.mouseY){
y += 1;
} else if (y > Board.mouseY){
y -= 1;
}
}
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return image;
}
/* public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT){
dx = -1;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 1;
}
if (key == KeyEvent.VK_UP) {
dy = -1;
}
if (key == KeyEvent.VK_DOWN) {
dy = 1;
}
}*/
/* public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = 0;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 0;
}
if (key == KeyEvent.VK_UP) {
dy = 0;
}
if (key == KeyEvent.VK_DOWN) {
dy = 0;
}
}*/
}
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Board extends JPanel implements ActionListener {
public static int mouseX;
public static int mouseY;
private Timer timer;
private SpaceCraft craft;
public Board() {
//addKeyListener(new TAdapter());
setFocusable(true);
setBackground(Color.GREEN);
setDoubleBuffered(true);
craft = new SpaceCraft();
timer = new Timer(5, this);
timer.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(craft.getImage(), craft.getX(), craft.getY(), this);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
public void actionPerformed(ActionEvent e) {
craft.move();
repaint();
}
public void mouseReleased(MouseEvent e) {
mouseX = e.getXOnScreen();
mouseY = e.getYOnScreen();
craft.move();
repaint();
}
/*private class TAdapter extends KeyAdapter {
public void keyReleased(KeyEvent e) {
craft.keyReleased(e);
}
public void keyPressed(KeyEvent e) {
craft.keyPressed(e);
}
}*/
}
import javax.swing.*;
import java.applet.*;
import java.awt.Dimension;
import java.net.*;
public class RType extends Applet {
Board b = new Board();
public void init() {
b.setPreferredSize(new Dimension(400, 400));
add(b);
}
}
最佳答案
您必须将MouseListener添加到面板Board
。
更改
public class Board extends JPanel implements ActionListener {
至
public class Board extends JPanel implements ActionListener,MouseListener {
在构造函数中添加
addMouseListener(this);