Beginner, help needed

0 Antonio Exposito · August 6, 2015
So I started making a program that just shows a rectangle move around the screen (as a way to get in to video game programming) but I've had a problem straight away. Right now all I want is to see the rectangle move from left to right, but what I actually see it multiple rectangles being painted to the screen 

package pee;

public class Main {

public static void main(String[] args) {
Frame frame = new Frame();
        frame.setVisible(true);
        
        while(true){
        frame.setX(frame.getX()+1);
        frame.removeAll();
        frame.revalidate();
        frame.repaint();
        }
}

}

package pee;

import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;


public class Frame extends JFrame{

private int x;
private int vx;
private int y = 200;
private int vy;

     public Frame(){
    super("The title");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(1200,900);
    setResizable(true); 
     }
     
      public void paint(Graphics g){
        g.setColor(Color.RED);
        g.drawRect(x, y, 50, 50);
     }
     
      public int getX(){
     return x;
      }
      public int getY(){
     return y;
      }
      public int getVX(){
     return vx;
      }
      public int getVY(){
     return vy;
      }

      public void setX(int x){
     this.x = x;
      }
      public void setY(int y){
     this.y = y;
      }
      public void setVX(int vx){
          this.vx = vx;
      }
      public void setVY(int vy){
     this.vy = vy;
      }

}

Any help would be appreciated!

Post a Reply

Replies

Oldest  Newest  Rating
0 Jeffrey Hong · August 9, 2015
Computers are very fast.
You may actually be painting them individually, but because your emulator loops thru the while loop possibly thousands of times a second, you will see a perpetual rectangle at every point.

How about this:

while(x%10000==0){
x+=1;
frame.setX(frame.getX()+1);
frame.removeAll();
frame.revalidate();
frame.repaint();
}
  • 1

Java / Android Development

107,161 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator