xkz_5413 2014-12-03 15:18 采纳率: 0%
浏览 2080

java里repaint在循环里的问题

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循环后才执行,怎么回事

  • 写回答

1条回答

  • Coursera 2014-12-03 16:23
    关注

    根据javadoc, “If this component is a lightweight component, this method causes a call to this component's paint method as soon as possible. Otherwise, this method causes a call to this component's update method as soon as possible.” repaint不能保证调用立刻刷新。JPanel实际上是调用update,merge你的请求之后进行刷新。如果你的确要求立刻刷新,你可以调用paintImmediately

    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮