Reputation: 57
Im try do do a mini game,but first i learn how to animate :) it will be a 2D game. So my problem is if i just try to draw a rectangle its work when i try to animate(i did lot of code but not work :( ) its not working.
Some one can help me to fix it or add some tips how can i try to do it.
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();
}
}
Upvotes: 0
Views: 257
Reputation: 5625
Your code works fine except you forget to add your Component (you named it Window
) into the Container (JFrame
in this case). To do that add f.add(this);
at the end of your Window()
constructor.
Take a look at swing-components-and-containers for more info.
Also I suggest you to take a look at Double-buffer-in-standard-Java-AWT and Game loops!
Upvotes: 2