Back Next

Converts from device to logical coordinates

This applet converts the x and y coordinates of the point you click on from Java device coordinates, i.e. with the origin in the top left hand corner and positive x going right and positive y going down, to logical x and y coordinates, i.e. with the origin in the bottom left hand corner and positive x going right and positive y going up.

Click anywhere in the box:

Code:

// logicalDevice.java: converts between logical and device coordinates

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class logicalDevice extends Applet

int x,y, maxX,maxY;
float logicX,logicY;

public void init()

setSize(500, 500);
this.addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent evt){x = evt.getX(); y = evt.getY();repaint();}});
show();
}

public void paint(Graphics g)

Dimension d = getSize();
maxX=d.width-1; 
maxY=d.height-1;
g.drawString("canvas number of pixels width = " + d.width, 10, 15);
g.drawString("canvas number of pixels height = " + d.height, 10, 30); 
g.drawString("point device x-coordinate = " + x, 10, 45);
g.drawString("point device y-coordinate = " + y, 10, 60);
g.drawString("maximum x-coordinate = " + maxX, 10, 75);
g.drawString("maximum y-coordinate = " + maxY, 10, 90);
logicX=(float)x;
logicY=(float)(maxY-y);
g.drawString("logical x-coordinate = " + logicX, 10, 105);
g.drawString("logical y-coordinate = " + logicY, 10, 120);
g.setColor(Color.blue);
g.drawLine(x,y,x,y);//draws a blue pixel at (x,y)
}
}

Up