Search code examples
java-2dcoordinate-systems

Is it possible in Java2D to move the coordinate system?


I need a 2D coordinate system to which renders a user space coordinate system to swing components on the screen. Now that is exactly what Java2D does. But what I need further is to move the relative position of the screen and the coordinate system to get a kind of scrolling.

In Java 2D the default offspring (0,0) is in the upper left corner which is common in computer graphics.

Is it possible to move the point? If yes: How can I do it?

Thanks in advance.


Solution

  • You can change your coordinate system using the translate() function. For example:

    Graphics2D g;                    // Assume this is already initialized
    g.drawLine(100, 100, 200, 200);  // Draw in the default coordinate system
    g.translate(100.0, 100.0);       // Move the origin down and to the right
    g.drawLine(0, 0, 100, 100);      // Draw the same line relative to new origin
    

    You can also use scale(), rotate() and shear() for more powerful transformations of the coordinate system. For more information check this page: http://docstore.mik.ua/orelly/java-ent/jfc/ch04_03.htm