I have a Object in JScrollPane. As Objects height increases and decreases, JScrollBars appear and disappear.

Is there a way to detect when this is happening?

I want to widen the whole JScrollPane when they appear so that Object doesn't get its rightmost part obstructed by JScrollBars and vice-versa.

有帮助吗?

解决方案

You can easily listen to component size changes like this:

    JPanel object = new JPanel ();
    object.addComponentListener ( new ComponentAdapter ()
    {
        public void componentResized ( ComponentEvent e )
        {
            // Your object size changed
        }
    } );

    JScrollPane scrollPane = new JScrollPane ( object );

But that might not solve your specific objective.

If you don't want scroll pane's vertical scroll bar to obstruct your object you could use a small trick to fool both - the scroll pane and your object. Check this example:

public class Example
{
    public static void main ( String[] args )
    {
        final MyObject object = new MyObject ();

        final JScrollPane scrollPane = new JScrollPane ( object )
        {
            public Dimension getPreferredSize ()
            {
                final Dimension ps = super.getPreferredSize ();
                final JScrollBar vsb = getVerticalScrollBar ();
                final Insets i = getInsets ();
                ps.width = object.getPreferredWidth () + ( vsb.isShowing () ? vsb.getPreferredSize ().width : 0 ) + i.left + i.right;
                return ps;
            }
        };
    }

    public static class MyObject extends JPanel
    {
        public Dimension getPreferredSize ()
        {
            final Dimension ps = super.getPreferredSize ();
            ps.width = 0;
            return ps;
        }

        public int getPreferredWidth ()
        {
            return super.getPreferredSize ().width;
        }
    }
}

This will force...

  1. ...component to return zero preferred width, so that scroll pane will always shrink it to its current inner view available width.

  2. ...scroll pane to return modified preferred width according to its actual content preferred width so it will still get the place it needs to display the object properly.

This example can be modified depending on the situation. For example it might be different for different container layouts where you might put your scroll pane.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top