java键盘事件不响应_java 键盘事件不响应.新手求助 求大佬.

importjava.awt.*;importjava.awt.event.KeyEvent;importjava.awt.event.KeyListener;importjava.awt.image.BufferedImage;importjavax.swing.*;publicclasspaintdemo1extendsJFrame{...

import java.awt.*;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.awt.image.BufferedImage;

import javax.swing.*;

public class paintdemo1 extends JFrame

{

public void langchFrame()

{

this.setTitle("动画练习");

this.setBounds(300, 250, 400, 400);

this.setDefaultCloseOperation(EXIT_ON_CLOSE);

MyPanel jp = new MyPanel();

add(jp);

this.setVisible(true);

jp.langchJp();

}

public static void main(String[] args){

paintdemo1 p = new paintdemo1();

p.langchFrame();

}

}

class MyPanel extends JPanel implements KeyListener

{

Image img = Tollsdemo.getImage("image/滑稽.png"); //一个获取图片在工具类

int x = 100; int y = 100;

int dx = 10; int dy = 0;

public void langchJp ()

{

new Re().start();

this.addKeyListener(this);

}

public void paint(Graphics g)

{

super.paint(g);

Color c = new Color(200,0,0);

g.setColor(c);

g.drawImage(img,x,y,null);

x+=dx; y+=dy;

if(x>330)

dx=-10;

if(x<0)

dx=10;

if(y>310)

dy=-10;

if(y<0)

dy=10;

}

class Re extends Thread

{

public void run()

{

while(true)

{

repaint();

try

{

this.sleep(40);

} catch (InterruptedException e)

{

e.printStackTrace();

}

}

}

}

public void keyTyped(KeyEvent e) {

}

public void keyPressed(KeyEvent e) {

if(e.getKeyCode()==KeyEvent.VK_UP){

dy=-10; dx = 0;}

if(e.getKeyCode()==KeyEvent.VK_DOWN){

dy=10; dx = 0;

}

if(e.getKeyCode()==KeyEvent.VK_LEFT){

dx=-10; dy=0;

}

if(e.getKeyCode()==KeyEvent.VK_RIGHT){

dx=10; dy=0;

}

}

public void keyReleased(KeyEvent e) {

}

}

展开

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页