问题
I am wondering what is the best way to retrieve the location of a mouse clic after a zoom was made using paintComponent of a panel? (The location relative to this zoom).
Here's the zoom code :
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if(zoomer==true){
at.scale(zoom,zoom);//at = AffineTransform...
zoomer=false;
}
g2.transform(at);
In my main class, I use a mouse listener private class and override the mouseRelase method :
@Override
public void mouseReleased(MouseEvent e)
e.getX();//Location of the mouse on the X axis
I am drawing different shapes such as dots. Every dot has it's Pixels locations stored so if a create it at X:20 and Y:30 this never changes. When I call paintComponent, it is scaled either bigger or smaller. My problem is, I can clic on the location of these dots on the panel and it gives me some information in some textFields about the dots I clicked on. If the panel has been zoomed in/out, the location of the clic is still the same so let's say I zoom in, the shapes won't be at x:20 and y:30 but at a random location based on the scale. How can I ajust my clic location to this scale?
Not sure if I am making myselft clear so do not hesitate if you need more information.
Thank you
回答1:
Alright, I have been working all night long and finally figured out how to do this.
First of all here's what happens when I roll the mouse wheel :
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
//Zoom in
if(e.getWheelRotation()<0){
mydrawer.setZoomFactor(1.1*mydrawer.getZoomFactor());
mydrawer.repaint();
}
//Zoom out
if(e.getWheelRotation()>0){
mydrawer.setZoomFactor(mydrawer.getZoomFactor()/1.1);
mydrawer.repaint();
}
}
The setZoomFactor method does this :
public void setZoomFactor(double factor){
if(factor<this.zoomFactor){
this.zoomFactor=this.zoomFactor/1.1;
}
else{
this.zoomFactor=factor;
}
this.zoomer=true;
}
After, when I call repaint() I transform my Graphics2D object to zoom like this :
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if(zoomer==true){
at = new AffineTransform();
at.scale(zoomFactor,zoomFactor);
zoomer=false;
g2.transform(at);
}
}
At this point, nothing really new... My problem was when I clicked on a drawn objet after zoom, I needed to ajust the clic location relative to the zoom factor. In my case, I needed the 0 of the Y axis to be at the bottom left corner instead of top left by default which is why I had to reverse the value based on the panel height :
@Override
public void mouseReleased(MouseEvent e) {
int myXLocationWithoutZoom = e.getX()*(1/myDrawer.getZoomFactor());
int myYLocationWithoutZoom = myPanel.getSize().height-((e.getY())*(1/myDrawer.getZoomFactor()));
If you figure out another way to do this or think I did not do it the good way, let me know.
Thank you
来源:https://stackoverflow.com/questions/33925884/zoom-in-and-out-of-jpanel