1个回答
展开全部
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
public class MoveTextDemo extends JFrame {
public static void main(String[] args) {
new MoveTextDemo();
}
private int x = 200;
private int y = 200;
public MoveTextDemo() {
this.setTitle("Move Text Demo");
this.setSize(800, 600);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
y -= 5;
break;
case KeyEvent.VK_DOWN:
y += 5;
break;
case KeyEvent.VK_LEFT:
x -= 5;
break;
case KeyEvent.VK_RIGHT:
x += 5;
break;
default:
break;
}
repaint();
}
});
this.setVisible(true);
}
public void paint(Graphics g) {
Image img = createImage(getWidth(), getHeight());
Graphics gg = img.getGraphics();
paintBuff(gg);
gg.dispose();
g.drawImage(img, 0, 0, null);
}
private void paintBuff(Graphics g) {
g.drawString("Hello World!", x, y);
}
}
按键盘上下左右。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询