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]
工作的代碼被用於繪製面板上的填充矩形。但是,當我啓動程序時,對象會移動,但面板不會重新繪製。如果我在程序運行時嘗試調整窗口大小,它會正確加載。只要我停止這樣做,面板或框架(不確定)不再重繪。所以我結束了一條線。重繪()不是在擺動
你覺得x會變成小於0嗎? –