package test05;
//import java.awt.Color;
//import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.*;
import javax.swing.*;
//import javax.swing.JFrame;
//import javax.swing.JPanel;
public class Show extends JFrame {
MyPanel mp = null;
public Show() {
mp = new MyPanel();
this.add(mp);
this.addKeyListener(mp);
//
this.setSize(900, 600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
Show show = new Show();
}
}
class MyPanel extends JPanel implements KeyListener {
int x = 200;
int y = 200;
public MyPanel() {
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLACK);
g.fillOval(200, 200, 10, 10);
g.setColor(Color.red);
g.fillOval(x, y, 5, 5);
System.out.println("aaa");
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println(this.x);
if (e.getKeyCode() == KeyEvent.VK_J) {
while (!(x >= 900 || x <= 0 || y >= 600 || y <= 0)) {
this.repaint();
System.out.println("b");
this.x -= 5;
System.out.println(x);
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.repaint();
}
System.out.println("cccccc");
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
就是这个循环的问题
if (e.getKeyCode() == KeyEvent.VK_J) {
while (!(x >= 900 || x <= 0 || y >= 600 || y <= 0)) {
this.repaint();
this.x -= 5;
this.repaint();
}
}
repaint在出while循环后才执行,怎么回事