Simon Maas
Simon Maas

Reputation: 9

JPanel paintComponent(...) doesnt work

My problem is easy to explain: i want a/some JPanels, added to a JFrame, to paint themself with an image. sadly the last thing does not work. for info: the image path is correct and the JPanel size is the same as the image size. thx for help :P

package frames;

import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import world.Terrain;

public class PanelTerrain extends JPanel {
private Image img;
private int x;
private int y;
private Image imga;

    public PanelTerrain(Terrain terra, int x, int y) {
        imga = new ImageIcon(terra.getPath()).getImage();
        this.x = x;
        this.y = y;
        this.setBounds(x, y, 8, 8);
        //this.setBackground(terra.getColor());
    }

    public void changeTerrain(Terrain t)
    {
        this.setVisible(false);
        this.setBackground(t.getColor());
        this.setVisible(true);
    }

  @Override
  public void paintComponent(Graphics g) {
      super.paintComponent(g);
        g.drawImage(imga, x, y, this);
  }                 
}

Upvotes: 1

Views: 283

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

One very big problem is your possible misuse of bounds and x and y. You're calling setBounds on the JPanel (something to avoid) but then drawing the image at some x and y that in all likelihood is way beyond the bounded size of your JPanel. Don't do this. for more complete help, please create and post your Minimal, Complete, and Verifiable example.

Here's what I think that you should do instead -- assuming that you want a grid of images, some of say earth, some water, some grass, ...

  • Create ImageIcons for the base images, one Icon for grass, one for water, etc...
  • Create a JPanel that uses a GridLayout, and fill it with a grid of JLabels.
  • Place those same JLabels in a 2-dimensional array of JLabel.
  • Swap the label icons where and when you need to change the image by calling setIcon(newIcon) on the JLabel.

For example, please see this answer of mine to a similar question as well as the other answers to the same question.

Upvotes: 2

vivianig
vivianig

Reputation: 183

My first guess is that you're passing the wrong x and y.The x and y in g.drawImage are the coordinates of the top left corner, not the size of the image, so usually they are set directly at 0 (that means, g.draWimage(imga, x, y, this).

Upvotes: 5

Related Questions