Search code examples
javaswingawtgraphics2djava-2d

Java 2D, Translation with the same amount on X and Y axis leads to different results


I'm just playing around with Java 2D for a weekend-project. What I try to accomplish is simply to load and draw an image at position 50,50 away from the origin. Now when I try to do exactly that, with

g2d.drawImage(imageLeft, 50, 50, 200, 200, null);

then I get the following:

Frankly, this confuses me a little bit. Why does the x-part of the translation get scaled differently than the y-part? What is going on here? Must be an obvious beginner's mistake, but I cannot figure it out the reason for this behavior for the life of me ;-)

The complete code I use to draw the image is:

final IsogenWindow window = new IsogenWindow();
final BufferedImage imageLeft = loadImage(new File(getClass().getResource("/texture/tile1.png").toURI()));
final Graphics2D g2d = Graphics2D)window.getGraphics();

window.setSize(1000, 1000);
window.setVisible(true);

g2d.drawImage(imageLeft, 50, 50, 200, 200, null);

EDIT 1: To try out DontRelaX' suggestion, I changed my code so a panel is added to the JFrame and its Graphic2D object is used for drawing:

getContentPane().setLayout(null);
this.renderPanel = new JPanel();
getContentPane().add(renderPanel);
final Graphics2D g2d = (Graphics2D)renderPanel.getGraphics();
...
g2d.drawImage(imageLeft, 50, 50, 200, 200, null);

Unfortunately, the result is still the same. But I think DontRelaX is on the right track. Any further suggestions?

EDIT 2: Basically DontRelaX' answer was correct. I indeed used not the renderPanel's Graphics2D but instead still the JFrame's Graphics2D object.

Cheers, nanoquack


Solution

  • Pixels count from left top corner of window, not gray place. Add panel to your window and draw on it.