I am playing around with the Graphics class. Here is my code for drawing an image at a certain location:
public class PixelManager extends JPanel {
private ArrayList<Pixel> pixels = new ArrayList<Pixel>();
public PixelManager() { }
public void addPixel(int posX, int posY, BufferedImage texture) {
pixels.add(new Pixel(posX, posY, texture));
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
for (Pixel pixel : pixels) {
g2d.drawImage(pixel.getTexture(), pixel.getX(), pixel.getY(), 20, 20, null);
}
g2d.dispose();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400,400);
}
}
Explanation: I am using this class as kind of an Pixel or Texture Manager. In the ArrayList I am saving some Pixels, which include a position and a texture. in de paintComponent Method I am iterating through the ArrayList and trying to draw them.
Pixel class:
public class Pixel extends JPanel{
private int _posX, _posY;
private static int _width = 20;
private BufferedImage _texture;
public Pixel(int posX, int posY, BufferedImage texture) {
_posX = posX;
_posY = posY;
_texture = texture;
}
//Getter und Setter
public int getPosY() {
return _posY;
}
public int getPosX() {
return _posX;
}
public void setPosY(int posY) {
_posY = posY;
}
public void setPosX(int posX) {
_posX = posX;
}
public BufferedImage getTexture() {
return _texture;
}
public void setTexture(BufferedImage texture) {
_texture = texture;
}
}
And the JFrame extending class:
public class Zeichnen extends JFrame {
static PixelManager pman;
public Zeichnen()
{
setTitle("Tutorial");
setSize(400, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
Zeichnen fenster = new Zeichnen();
pman = new PixelManager();
fenster.add(pman);
try {
pman.addPixel(100, 100, ImageIO.read(new File("C:\\Users\\Cronax3\\Documents\\grass.jpg")));
pman.addPixel(200, 200, ImageIO.read(new File("C:\\\\Users\\\\Cronax3\\\\Documents\\\\blue.png")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
So here is the problem. The two images will be drawn to the panel/frame but ALWAYS to the postion x=0,y=0. I debuged everything until this line:
g2d.drawImage(pixel.getTexture(), pixel.getX(), pixel.getY(), 20, 20, null);
The values provided by pixel are correct. drawImage will receive the correct position and the correct texture/Image.
Becaus I am new to Graphics I would like to ask you guys helping me out with this problem.
Big Thanks in advance!
Greetz Cronax3