Results 1 to 2 of 2
- 06-20-2011, 07:44 AM #1
Member
- Join Date
- Jun 2011
- Posts
- 1
- Rep Power
- 0
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:
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?Java Code:*note: this class implements Runnable* int i = 0; Thread t = new Thread(this); public CLASSNAME() { t.start(); //do everything else } /* All Painting Code Goes Here */ public void paint(Graphics g) { g.drawImage("http://www.java-forums.org/images/player.png", 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 { t.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } //delay } }
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!
- 06-20-2011, 08:35 AM #2
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)
db
Similar Threads
-
Why only one of the two rectangles is painted?
By JOHNINALBANY in forum Java 2DReplies: 5Last Post: 07-07-2012, 10:54 PM -
how to remove images drawn by using Graphics Object
By usha in forum AWT / SwingReplies: 1Last Post: 12-04-2010, 03:07 PM -
how to know when jframe swing is painted
By petmoreno in forum AWT / SwingReplies: 1Last Post: 11-02-2010, 07:06 PM -
problem: lightweight component still being painted after remove
By LittleRave in forum AWT / SwingReplies: 3Last Post: 12-10-2009, 03:07 PM -
how to remove an image icon
By cecily in forum Advanced JavaReplies: 1Last Post: 08-05-2007, 04:25 AM


1Likes
LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks