java问题02-事件监听的问题

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame; public class Test04 extends JFrame implements KeyListener {

static int i = 1;
int x = 0, y = 0; public static void main(String[] args) {
new Test04();
} public void paint(Graphics g) {
super.paint(g);
g.clearRect(100, 100, 100, 200);
this.setBackground(new Color(this.x,this.y,0,255));
System.out.println("按下***************i=" + (i++));
System.out.println("this.x=" + this.x + "\n" + "this.y=" + this.y);
} public Test04() {

this.addKeyListener(this);
this.setTitle("颜色");
this.setSize(300, 400);
this.getContentPane()
.setBackground(new Color(0,0,255,255));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true); } public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SPACE) {
this.x = 200;
System.out.println("按下***************i=" + (i++));
try {
Thread.sleep(30);//按空格键,中间的矩形,由黑色变红色,一会再变黄色,但是如果是睡眠300毫秒的话,直接是由黑色直接变成黄色,根本不重绘了(我设置的输出信息可以看出来),时间大点就这样,不知这个是什么原因?想不出个为什么来
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.repaint();
} } public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
this.y = 200;
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.repaint();
System.out.println("释放********i=" + (i++));
} } public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub } }

你可能感兴趣的:(java问题02-事件监听的问题)