Repainting/refreshing the JFrame

前端 未结 3 1611
暗喜
暗喜 2021-01-21 07:18

I have a \"car\" made with various objects using graphics g and I want to move it when a button is pressed. With that, I had no problem, but I have a problem with its path. When

3条回答
  •  遇见更好的自我
    2021-01-21 07:48

    You should never be calling sleep() on the UI thread. Instead, I highly recommend that you use javax.swing.Timer and an ActionListener. Something like:

     void paintCar(Graphics2D g2d, int x) {
        g2d.setColor(Color.blue);
        g2d.fillRect(x+10, 351, 118, 23);
        g2d.fillRect(x+12, 321, 30, 40);
        g2d.fillRect(x+45, 330, 83, 20);
        g2d.setColor(Color.black);      
        g2d.fillOval(x+19, 362, 20, 20);
        g2d.fillOval(x+90, 362, 20, 20);
        g2d.drawString("2t", x+70, 344);
    }       
    
    int x = 0;
    public MyConstructor() {
      new Timer(5, this).start();
    }
    
    public void actionPerformed(ActionEvent ae) {
      x++;
      repaint();
    }
    
    public void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2d = (Graphics2D) g;
      paintCar(g2d, x);
    }
    

提交回复
热议问题