Graphics: Coordinate Issues
Hi Im having problems with graphics:
Im trying to draw images using 'Graphics' in a 'Paint' method based on the coordinates given by 'MouseEvents' in a 'JPanel'.
The problem is the JPanel doesnt start in the top left (theres a toolbar Panel down the west side), the Coordinates Paint uses are absolute coordinates, so 0,0 is the top left of the whole application window, but the MouseEvents return coordinates relative to the JPanel, so the top left of the JPanel is 0,0.
Ive bodged a solution by giving all the images I draw integer offsets but clearly this is a pain.
What Id like to know is;
can I make the Paint routine use coordinates of a specific JPanel?
or, can I make the mouseEvents return abolute coordinates?
thanks in advance
> can I make the Paint routine use coordinates of a
> specific JPanel?
Yes. Override the paintComponent() method of that specific JPanel.
> or, can I make the mouseEvents return abolute
> coordinates?
You can make use of the getLocationOnScreen() method of the JPanel that has the MouseMotionListener. I think version 1.6 also has a method for this in MouseEvent (though I'm not sure).
If I've understood you correctly, you wanted the co-ordinates of the frame and not the jpanel.
In that case you should add the mouse listener to the frame instead of the jpanel like this
frame.addMouseListener(this);
Just a sample code, here the frame is an object of the FRAME or JFRAME.
Let us know your progress.
Regards
Ive come to the conclusion that my paint method is overriding some kind of master method that redraws the entire app window, because the coordinates it uses really seem to be the very top left as origin (right up on the titlebar).
Below is the paint method Im using, so far the program only needs to repaint one JPanel (main) but soon I will be at the stage where multiple panels need to be repainted, I think I need to have a seperate paint method for each panel, so that each method uses that panels coordinates but I dont know so much about overriding methods and inheritance etc.
public void paint(Graphics g)
{
int xOffset = mainLocation.x;
int yOffset = mainLocation.y;
if(newClassMode == 2)
{
g.setColor(Color.gray);
g.drawRect(newClassCoords[0] + xOffset, newClassCoords[1] + yOffset,
dragX - newClassCoords[0], dragY - newClassCoords[1]);
}
if(mainDocument.classesList.length != 0)
{
for(int i=0; i<mainDocument.classesList.length; i++)
{
ClassBox c = mainDocument.classesList[i];
g.setColor(Color.black);
g.drawRect(c.xPosition + xOffset, c.yPosition + yOffset, c.width, c.height);
g.setColor(Color.white);
g.fillRect(c.xPosition + 1 + xOffset, c.yPosition + 1 + yOffset, c.width - 2, c.height - 2);
}
}
}
>