Moving a Java Swing Graphic
Question: I want to recreate a game I made in Python and after learning the basics of
Swing, I moved on to drawing Graphics. Now I'm stuck. I created a black square
and would like to move its coordinates by 10 to the right. What I want is to
be able to make an animation by moving the square and be able to respond to
the user's actions. Right now all I want is when the window is created (now),
at run time for the square to be redrawn 10 pixels to the right.

In Python Tkinter this was easy:

    
    
    square = myCanvas.create_rectangle(10, 10, 20, 20)
    

then later in the code, I would do this:

    
    
    x = 10
    while True:
        x = x + 10
        myCanvas.coords(square, x, y, x+10, y+20)
        time.sleep(0.1)
        myMainWindow.update()
    

It would move the square to the right for ever.

Here is my Java code:

    
    
    package tutorial2;
    
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class Tutorial2 {
    
        public static void main(String[] args) {
            make_gui();
        }
        static void make_gui(){
            JFrame f = new JFrame("My Window");
            f.getContentPane().setPreferredSize(new Dimension(500, 300));
    
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(new MyPanel());
            f.pack();
            f.setVisible(true);
        }
    }
    
    class MyRectangle extends Rectangle{
        Rectangle self;
        int x;
        int y;
        public MyRectangle(int x, int y){
              this.x = x;
              this.y = y;
              this.self = new Rectangle(this.x, this.y, this.x+10, this.y+10);
        }
    
    }
    
    class MyPanel extends JPanel{
        MyRectangle user = new MyRectangle(10, 10);
        Rectangle user2 = new Rectangle(30, 30, 40, 40);
        public MyPanel(){
    
        };
    
        public void paintComponent(Graphics g){
            Graphics2D graphics2d = (Graphics2D) g;
            //graphics2d.fill(user2);
            graphics2d.fill(user.self);
        }
    }
    

How do I do it in here?


Answer: Just use:

    
    
    g.drawRect(x1,y1,width,height);
    

Or:

    
    
    g.fillRect(x1,y1,width,height);
    

You don't need a `Rectangle` object or your own `MyRectangle` object.

You can store the coordinates and update them every frame.

