以下是我从YouTube视频中复制的代码。我不知道为什么g.fillRect(x,10,20,20);没有显示。我检查了几次,仍然可以在代码中找到错误。请帮我找出问题所在:(
package sanke.playground;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class SankePlayground extends JPanel implements ActionListener {
Timer tm = new Timer (5,this);
int x = 0, velX = 2;
//int y = 0, velY = 0;
public SankePlayground(){
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(x, 10, 20, 20);
tm.start();
}
public void actionPerformed(ActionEvent e){
x = x+ velX;
repaint();
}
public static void main(String args[]){
SankePlayground t = new SankePlayground();
JFrame jf = new JFrame();
jf.setSize(600,400);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(t);
}
}