0

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

Samuel
  • 21
  • 5
  • 1
    Mouse events will *never* change to match your zoom. There is no concept of zoom in Swing. You have to do the math yourself in your (mouse) listeners. As for the scrollbars being "too long", again its *your code* that controls the preferred size of your panel - set it properly for the zoom level and the scrollbars will match it. Also you should *never* dispose the graphics object passed to your paintComponent method. – Durandal Dec 09 '15 at 17:24
  • You can actually do what you're trying to do with the use of JXLayer/JLayer. The linked duplicate question/answer has runnable example which will not only allow you to scale the graphics but also the events as they occur, what's really cool about this, is it works basically on all Swing based components – MadProgrammer Dec 09 '15 at 22:56

1 Answers1

0

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().

Samuel
  • 21
  • 5