[英]Java Swing Try to make a little animation with rectangle
我嘗試做一個迷你游戲,但首先我要學習動畫:)這將是一個2D游戲。 所以我的問題是,當我嘗試制作動畫時,如果我只是嘗試繪制一個矩形的工作(我做了很多代碼但沒有工作:()它沒有工作。
有人可以幫助我修復它或添加一些提示,我如何嘗試做到這一點。
public class Window extends JPanel implements ActionListener {
Timer tm = new Timer(5 , this);
int x2 = 0 , velX = 2;
static int x= 500;
static int y= 500;
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(x2, 30, 30, 30);
tm.start();
}
public Window(){
JFrame f = new JFrame();
f.pack();
f.setTitle("Game");
f.setSize(x,y);
f.setVisible(true);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
}
/*public void paint(Graphics g){
Graphics2D g2d = (Graphics2D) g;
Rectangle rect = new Rectangle(50, 50, 50, 50);
g2d.translate(25, 25);
g2d.rotate(Math.toRadians(45));
g2d.draw(rect);
}*/
public static void main(String [] args) throws InterruptedException{
Game g = new Game();
g.setName("Test");
System.out.println(g.getName());
g.setScore();
}
@Override
public void actionPerformed(ActionEvent e) {
x2 = x2 + velX;
repaint();
}
}
您的代碼工作正常,除非您忘記將Component(您命名為Window
)添加到Container(在本例中為JFrame
)中。 為此,添加f.add(this);
在Window()
構造函數的末尾。
看一下秋千組件和容器以獲取更多信息。
我還建議您看一看標准Java-AWT中的Double-buffer和Game循環!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.