Yayatcm
Yayatcm

Reputation: 203

Java how to draw on JPanel from another method?

I want to use a method to get what you are trying to draw (getImage() method) but I cant figure out how to draw it in to the paint method. Here it is so far:

public void getImage(String location,int x,int y,int size){
    Image image = new ImageIcon(location).getImage();
    //paint(image); Thats my question
}
public void paint(Graphics g){
}

Thanks :)

Upvotes: 2

Views: 2324

Answers (2)

mastrgamr
mastrgamr

Reputation: 631

You need to setup a class that extends from JPanel and another class unrelated to it that describes the image you are trying to draw.

Let's say you have two classes, Window (that extends JPanel), and Image (where you load the image to be drawn in the JPanel)

If you want to draw an image from Image into the Window class you have to instantiate Image in the Window class.

Image should have a method in it that can be used in Window to draw the image in Window like so:

private void drawMe(Graphics g){
    g.drawImage(someImage, x, y, null);
}

and in your Window class (that extends from JPanel) I recommend you override the paintComponent method, not paint. In that method you should call Image's drawMe() method and pass Graphics as an argument. Like so:

private Image image = new Image("filePath.jpg", 10, 10); //based on the arguments you setup in the contructor

public void paintComponent(Graphics g){
    image.drawMe(g); //access Image's drawMe() method and pass graphics to it
}

All drawing and image location is handled by the Image class, all you'r doing with the Window class is making it show up on the JPanel.

Upvotes: 1

Simon
Simon

Reputation: 1851

Uhm, you can't do this easily. What you can do however is to force a repaint by calling the repaint() method and then paint the new image in the paint method.

The code will look something like this:

private Image someImage;
public void getImage(...)
{
  someImage = new ImageIcon(location).getImage();
  repaint(); //will make java call the paint-method in a moment
}

public void paint(Graphics g)
{
  if(someImage!=null)
    //paint someImage here
}

There's a long article about how Painting in AWT and Swing works. Be sure to read the very short chapter Swing Painting Guidelines which contains the most important take-aways.

Upvotes: 1

Related Questions