重绘()在摆动中不起作用

repaint() is not working in swing

package games;

import java.awt.*;   
import java.awt.event.*;   
import javax.swing.*;    

public class viza extends JPanel implements ActionListener {       

/**   
     *   
     */  
    private static final long serialVersionUID = 1L;      
    int x=0, y=200;
    Timer tm =new Timer(5,this);     
    public viza(){    
        tm.start();    
    }    
    public void paintComponent(Graphics g){    
        g.setColor(Color.red);    
        g.fillRect(x, y, 20, 20);    
    }     
    public void actionPerformed(ActionEvent e){   
        x=x+1;   
        y=y+1;   
        if(x>300)    
           x=0;      
        if(x<0)   
            x=0;        
        repaint();   //after x and y are changet then I use repaint();
    }     // the frame is created and the new object is added into the frame.
    public static void main(String[] args){     
        viza a=new viza();     
        JFrame frame = new JFrame();     
        frame.setSize(500,500);          
        frame.add(a);      
        frame.setVisible(true);         
    }     
}[1]      

该代码用于在面板上绘制一个填充的矩形。然而,当我启动程序时,对象移动但面板没有重新绘制。如果我在程序运行时尝试调整 window 的大小,它会正确加载。一旦我停止这样做,面板或框架(不确定)就不再重新粉刷了。所以我最终得到了一条线。

在新位置重新绘制矩形之前,您应该清除底层窗格。

要做到这一点,让 super.paintComponent() 为您做到这一点,因为这将是任何 JComponent:

中自定义绘画的正确方法
public void paintComponent(Graphics g){    
    super.paintComponent(g); // let it do the default paint
    g.setColor(Color.red);    
    g.fillRect(x, y, 20, 20);    
}

您可能还想为您的框架添加默认关闭操作(在 main 方法中)以在关闭框架后退出程序:

frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

另一个提示是为您的计时器设置更大的 timeout,因为 5 毫秒发生得非常快,您的用户可能看不到运动。尝试比 50100.

更大的东西

祝你好运。