简体   繁体   中英

Update JscrollBar without resetting position

I have a class which extends JScrollPane, its viewport is another class which extends JComponent and implements Scrollable. When the size of the component changes the JscrollBars do not update unless I call revalidate() however this resets the position of the scroll bars to the top left. Is there a way of updating the size of the scroll bars while maintaining their current position?

Thanks, Rob

Is the problem your custom scroll pane or your custom component? We can't begin to guess what kind of changes you may have made. Post your SSCCE that demonstrates the problem.

It works fine for me.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ScrollSSCCE extends JPanel
{
    public ScrollSSCCE()
    {
        setLayout( new BorderLayout() );

        final JPanel panel = new JPanel();
        panel.setPreferredSize( new Dimension(200, 200) );
        JScrollPane scrollPane = new JScrollPane( panel );
        add( scrollPane );

        JButton button = new JButton("Adjust");
        add(button, BorderLayout.SOUTH);
        button.addActionListener( new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                Dimension d = panel.getPreferredSize();
                d.width +=50;
                d.height +=50;
                panel.setPreferredSize(d);
                panel.revalidate();
            }
        });
    }

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("ScrollSSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new ScrollSSCCE() );
        frame.setSize(150, 150);
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM