2

I am making a game in which I move a square with my mouse, but when I move my mouse the old squares do not delete, which results in a trail of squares. I would like it to only have the one square which is following my mouse. This is currently my code. I have read to use paintcomponents but I am not sure how to use it since I am still a beginner.

This is in my "GamePanel" Class

public void mouseMoved(MouseEvent m) {

        Graphics g= this.getGraphics();
        h.changeX(m.getX());
        h.changeY(m.getY());
        h.drawHero(g);

    }

This is in my "Hero" Class

public void drawHero(Graphics g){

        g.drawImage(heroPic,stX,stY,null); //heroPic is a picture I imported
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
Biggiebhar
  • 21
  • 1
  • Don't draw directly on `JFrame`. Use `JPanel` to draw on it. Find a sample code here [How to draw in jPanel? (swing/graphics Java)](http://stackoverflow.com/questions/6118737/how-to-draw-in-jpanel-swing-graphics-java?answertab=votes#tab-top) – Braj Apr 18 '14 at 23:09
  • _"I have read to use `paintcomponents`"_ - Actually you want `paintComponent`, no `s` – Paul Samsotha Apr 19 '14 at 02:43

2 Answers2

2

Don't use the this.getGraphics(). That is something you will definitely not want to to do, since it produces artifacts (as you mentioned).

It would be better to store the mouse position as a variable, then handle all the rendering when the paintComponent(Graphics) method has been called. Be sure to also call super.paintComponent(Graphics) to get rid of artifacts.

Generally, you should only handle graphics inside the paintComponent(Graphics) method and in any methods that are called only from the paintComponent(Graphics) method.


Here is a question which touches on why you should avoid Component#getGraphics(): Drawing an object using getGraphics() without extending JFrame


Here is another question I answered revolving around rendering with graphics: Java JFrame draw

Community
  • 1
  • 1
Obicere
  • 2,999
  • 3
  • 20
  • 31
0

Use a seperate class that extends JPanel :

class DrawPane extends JPanel {
 public void paintComponent(Graphics g) {
  super.paintComponent(g);
  g.drawImage(heroPic, x, y, this);

 }


}

Then create a variable that will hold this class object :

DrawPane dp = new DrawPane();

after that set the variable to the contence pane. :

JFrame.setContencePane(dp);

Now to repaint this do :

 dp.repaint();

Do not worry about the 'Graphics g' you wont have to input anything.