java - 调用 repaint 不会导致在线程中调用 Paint 方法

标签 java swing

由于鼠标按下事件,正在执行以下线程:

// simulates bouncing ball
class Ball extends JPanel implements Runnable {  
  int Horz = 200;  
  int Vert = 200;  
  int xDim = 10;  
  int yDim = 10;  
  private int xPos;  
  private int yPos;  
  private int dxPos;  
  private int dyPos;  

  // constructor - set initial ball position to where mouse clicked; deltas to random numbers
  public Ball(int startx, int starty)  
  {  
    xPos   = startx;  
    yPos   = starty;  
    dxPos =  (int) (Math.random() * 5 + 2);  
    dyPos =  (int) (Math.random() * 5 + 2);  
  }
  // logic to update position of ball
  public void move() {

    xPos += dxPos;
    yPos += dyPos;

    if (xPos < 0) {
      xPos = 0;
      dxPos = -dxPos;
    }
    if (xPos + xDim >= Horz) {
      xPos = Horz - xDim;
      dxPos = -dxPos;
    }
    if (yPos < 0) {
      yPos = 0;
      dyPos = -dyPos;
    }

    if (yPos + yDim >= Vert) {
      yPos = Vert - yDim;
      dyPos = -dyPos;
    }
  }

调用 Run 方法,该方法调用重绘

  @Override
  // run --- paint, sleep, update position - this is being executed
  public void run()     
  {  
    while (true)  
    {         
        System.out.println("I am in RUN");  
        repaint();  

        try
        {
            // sleep thread for 20 milliseconds
            Thread.sleep(20);
        }
        catch (InterruptedException e)
        {
            // interrupted
            System.out.println("Terminated prematurely due to interruption");
        }

        move();               
    }   
  }

但是paint没有被调用

     // draw ball at current position  
     @Override  
     public void paint( Graphics g )  
     {  
       // THIS IS NOT BEING EXECUTED  
       System.out.println("I am in paint");  

       super.paint( g );  
       g.setColor( Color.BLUE );   
       g.fillOval( xPos, yPos, 10, 10 );   
    }   
}

这是为什么呢? repaint 不应该调用 Paint 方法吗?

最佳答案

Repaint 不会立即调用 Paint;它安排要重新绘制的组件,这将导致事件队列到达它时立即调用绘制。您很可能正在阻止 event dispatch thread通过在其上运行计时器循环,因此它无法处理绘制事件(或任何其他事件)。在不同的线程上运行循环,或者(更简单、更安全)将其替换为 Swing Timer :

Timer t = new Timer(20, (ActionEvent e) -> {
    move();
    repaint();
});
t.start();

关于java - 调用 repaint 不会导致在线程中调用 Paint 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27645967/

相关文章:

java - Eclipse 编译器合规性错误 1.6

java - GWT 表示层 : Who does what?

java - 无法获取父级的哈希码并将其设置为子级的变量

java - 单击 jButton 时如何更改单个椭圆的颜色?

java - REST API - 返回具有不同数据的资源列表

java - Apache Avro 和 Spring Data?

java - ColorBlobDetector 无法乘以轮廓

java - 绘图到按钮单击

java - JOptionPane 或更好的解决方案

java - 结果集存储到带有单元渲染的表的字符串数组中