[英]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]
该代码用于在面板上绘制一个填充的矩形。 但是,当我启动程序时,对象会移动,但面板不会重新粉刷。 如果我在程序运行时尝试调整窗口大小,则会正确加载。 一旦我停止这样做,面板或框架(不确定)就不会重新粉刷了。 所以我结束了一条线。
在将矩形重新绘制到新位置之前,应先清除基础窗格。
为此,请让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
毫秒的发生非常快,并且用户可能看不到该运动。 尝试大于50
或100
东西。
祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.