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

    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记