java – 如何使用箭头键在屏幕上移动图形?
作者:互联网
我正在努力创造一个简单游戏的开始.我要做的第一件事是将图形导入我的代码并在屏幕上移动它.我能够在屏幕上画一个球并移动它,但是当我从文件中导入图形时,我无法移动它.我错过了什么或做错了什么?
import javax.swing.*;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.*;
import javax.swing.ImageIcon;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Game extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
double x = 0, y = 0, velX = 0, velY = 0;
private ImageIcon image;
public Game(){
setBackground(Color.WHITE);
t.start();
addKeyListener(this);
this.setFocusable(true);
setFocusTraversalKeysEnabled(false);
image = new ImageIcon ("ship.gif");
}
public void paintComponent(Graphics g){
super.paintComponent(g);
ImageIcon i = new ImageIcon("C:\\Users\\Bryan\\Pictures\\ship.gif");
i.paintIcon(this, g, 0, 0);
}
public void actionPerformed(ActionEvent e){
repaint();
x += velX;
y += velY;
if(x<0){
velX = 0;
x = 0;
}
if(x>750){
velX = 0;
x = 750;
}
if(y<0);{
velY = 0;
y = 0;
}
if(y>550){
velY = 0;
y = 550;
}
}
public void up(){
velY = -1.5;
velX = 0;
}
public void down(){
velY = 1.5;
velX = 0;
}
public void left(){
velX = -1.5;
velY = 0;
}
public void right(){
velX = 1.5;
velY = 0;
}
public void keyPressed(KeyEvent e){
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP){
up();
}
if (code == KeyEvent.VK_DOWN){
down();
}
if (code == KeyEvent.VK_LEFT){
left();
}
if (code == KeyEvent.VK_RIGHT){
right();
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){
// velX = 0;
// velY = 0;
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP){
velY = 0;
}
if (code == KeyEvent.VK_DOWN){
velY = 0;
}
if (code == KeyEvent.VK_LEFT){
velX = 0;
}
if (code == KeyEvent.VK_RIGHT){
velX = 0;
}
}
}
我的驱动程序在另一个类中,如下所示:
import java.awt.Color;
import javax.swing.JFrame;
public class GameDriver {
public static void main(String[] args) {
JFrame f = new JFrame();
Game g = new Game();
f.add(g);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(800,600);
}
}
解决方法:
这里有两大问题:
public void paintComponent(Graphics g){
super.paintComponent(g);
ImageIcon i = new ImageIcon("C:\\Users\\Bryan\\Pictures\\ship.gif");
i.paintIcon(this, g, 0, 0);
}
>您正在从paintComponent(…)中的文件中读取.永远不要这样做因为这会不必要地减慢您的绘图速度.可能在构造函数中读取一次图像,然后在绘图中使用存储的图像变量. paintComponent方法应仅用于绘画,它应该是精益,平均和快速的.
>你总是在0,0处画画.如果要移动某些内容,请在可变位置绘制,然后更改变量保留的值并重新绘制.
另外:您应该使用键绑定来接受Swing应用程序中的击键,因为这将有助于解决焦点问题.
例如,请查看我在this answer的代码.
标签:java-2d,java,swing 来源: https://codeday.me/bug/20191008/1875354.html