javaswingpaintjviewport

How to draw a Guide Marker for the Viewport of JScrollPane


I have JFrame, which contains a Jscrollpane which in turn contains a Jpanel with image being displayed in it. All the mouse events and drawing is respect to the Jpanel cordinates. Now, I want to put a guide lines marker on top of the ViewPort, The marker should remain constant irrespective of the image being zoomed or panned. What is the best way to do it? Thanks in advance.

https://i.sstatic.net/m4qe2.png


Solution

  • You can do custom painting on the viewport of the scroll pane:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    
    public class ViewportBackground
    {
        private static void createAndShowUI()
        {
            JViewport viewport = new JViewport()
            {
                @Override
                protected void paintChildren(Graphics g)
                {
                    super.paintChildren(g);
                    int w = this.getWidth();
                    int h = this.getHeight();
                    g.drawLine(0, 0, w, h);
                }
            };
    
            JScrollPane scrollPane = new JScrollPane();
            scrollPane.setViewport(viewport);
            scrollPane.setViewportView( new JLabel( new ImageIcon(...) ) );
    
            JFrame frame = new JFrame("Viewport Background");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add( scrollPane );
            frame.setLocationByPlatform( true );
            frame.pack();
            frame.setVisible( true );
        }
    
        public static void main(String[] args)
        {
            EventQueue.invokeLater(new Runnable()
            {
                public void run()
                {
                    createAndShowUI();
                }
            });
        }
    }