I am currently trying to figure out how to zoom in a JPanel
that has graphics drawn on it. The JPanel
is currently embedded in a JScrollPane
, which should allow the user to scroll when the zoom level is above 100%.
Right now, I am able to zoom in the panel properly, but the AffineTransform is not applied to the mouse events. Also, when the scrollBars
are visible, they are way too long. I don't want them to be longer than the original size of the JPanel
.
private AffineTransform m_zoom;
@Override
protected void paintComponent(Graphics p_g) {
if (m_mainWindow != null) {
m_zoom = ((Graphics2D) p_g).getTransform();
m_zoom.scale(m_scale, m_scale);
((Graphics2D) p_g).transform(m_zoom);
super.paintComponent(p_g);
}
p_g.dispose();
}
public void setScale(double p_scale) {
m_scale = p_scale;
repaint();
revalidate();
}
If someone could help me with all this, that would be very appreciated! Thank you
Ok I figured out what was going on with the JScrollPane
. I adjusted the size of the JPanel
manually according to new zoom level and it worked.
public void setScale(double p_newScale) {
m_scale = p_newScale;
int width = (int) (getWidth() * m_scale);
int height = (int) (getHeight() * m_scale);
setPreferredSize(new Dimension(width, height));
repaint();
revalidate();
}
I still need to find a way to calculate the position of the mouse with the JPanel
zoomed in/out. Should I override the mouseClicked
and mouseMoved
methods directly in my custom JPanel
class?
EDIT:
I used a simple division for the relative coordinates on my JPanel. It worked out very well for both mouseMoved and mouseClicked.
Point zoomedLocation = new Point((int)(evt.getPoint().x / m_zoomFactor),
(int)(evt.getPoint().y / m_zoomFactor));
And I am using zoomedLocation
everywhere instead of evt.getPoint()
.