Results 1 to 2 of 2
Like Tree1Likes
  • 1 Post By DarrylBurke

Thread: Remove Painted Image From Graphics

  1. #1
    Ternary is offline Member
    Join Date
    Jun 2011
    Rep Power

    Default Remove Painted Image From Graphics

    Hello. I have just started programming a top down first person shooter game. In order to paint the player, I need to use Graphics to put it on the screen. Below is some code:

    Java Code:
    *note: this class implements Runnable*
    int i = 0;
    Thread t = new Thread(this);
    public CLASSNAME() {
      //do everything else
    /* All Painting Code Goes Here */
    	public void paint(Graphics g) {
    		g.drawImage("", i, 50, null);	//Arguments: image, x-length (from left), y-length (from top), null
    	/* Main/Update Loop */
    	public void run() {
    		for(;;) {
    			//update game state (update position and animation)
    			i += 10;
    			repaint();	//calls paint(Graphics g)
    			try {
    			} catch (InterruptedException e) {
    The paint method repeatedly paints the player image every time it is called, creating more images on the screen every time it is called. How can I make it so there is only one image on the screen at a time and make it so that the previous one gets removed?

    Also, I have tried the clearRect() method which fills a selected area with the background color. However, the image still stays in the memory, so this doesn't completely remove it.

    Thanks in advance for helpful replies!

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Madgaon, Goa, India
    Rep Power


    First off, and not what you asked: don't use an update loop, use a javax.swing.Timer.

    Second, if you're drawing to a Swing component, the method to override is paintComponent(...), not paint(...). And if you're drawing to a top level window, that's wrong.

    Third, any override of a painting method that doesn't fill the entire display area should start with invoking the super implementation.

    Recommended reading:
    Lesson: Performing Custom Painting (The Java™ Tutorials > Creating a GUI With JFC/Swing)
    How to Use Swing Timers (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)

    Fubarable likes this.

Similar Threads

  1. Why only one of the two rectangles is painted?
    By JOHNINALBANY in forum Java 2D
    Replies: 5
    Last Post: 07-07-2012, 10:54 PM
  2. Replies: 1
    Last Post: 12-04-2010, 03:07 PM
  3. how to know when jframe swing is painted
    By petmoreno in forum AWT / Swing
    Replies: 1
    Last Post: 11-02-2010, 07:06 PM
  4. Replies: 3
    Last Post: 12-10-2009, 03:07 PM
  5. how to remove an image icon
    By cecily in forum Advanced Java
    Replies: 1
    Last Post: 08-05-2007, 04:25 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts