Scroll JScrollPane to bottom

前端 未结 12 837
庸人自扰
庸人自扰 2020-11-30 02:18

I need to scroll a JScrollPane to the bottom. The JScrollPane contains a JPanel, which contains a number of JLabel\'s.

To scroll to the top, I just do:



        
相关标签:
12条回答
  • 2020-11-30 02:56

    I adapted the code of Peter Saitz. This version leaves the scrollbar working after it has finished scrolling down.

    private void scrollToBottom(JScrollPane scrollPane) {
        JScrollBar verticalBar = scrollPane.getVerticalScrollBar();
        AdjustmentListener downScroller = new AdjustmentListener() {
            @Override
            public void adjustmentValueChanged(AdjustmentEvent e) {
                Adjustable adjustable = e.getAdjustable();
                adjustable.setValue(adjustable.getMaximum());
                verticalBar.removeAdjustmentListener(this);
            }
        };
        verticalBar.addAdjustmentListener(downScroller);
    }
    
    0 讨论(0)
  • 2020-11-30 02:56

    I have tried several method. Some use bar.setValue(bar.getMaximum()), but the maximum is always 100 while the range of bar will be much more than 100. Some use textArea, but it is not suitable for that there is only a JTable in the JScrollPane. And I thing about a method, maybe stupid but effective.

    JScrollBar bar=jsp.getVerticalScrollBar();
    int x=bar.getValue();
    for(int i=100;i<2000000000;i+=100)
    {
        bar.setValue(i);
        if(x==bar.getValue())
            break;
        x=bar.getValue();
    }
    
    0 讨论(0)
  • 2020-11-30 02:57

    If your JScrollPane only contains a JTextArea then:

    JScrollPane.getViewport().setViewPosition(new Point(0,JTextArea.getDocument().getLength()));
    
    0 讨论(0)
  • 2020-11-30 02:57
    ScrollBar vertical = scrollPane.getVerticalScrollBar();
    vertical.setValue( vertical.getMaximum() - 1 );
    

    just set value to: vertical.getMaximum() - 1

    0 讨论(0)
  • 2020-11-30 03:03
    scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {  
        public void adjustmentValueChanged(AdjustmentEvent e) {  
            e.getAdjustable().setValue(e.getAdjustable().getMaximum());  
        }
    });
    
    0 讨论(0)
  • 2020-11-30 03:04

    None of the answers worked for me. For some reason my JScrollPane was not scrolling to the very bottom, even if I revalidated everything.

    This is what worked for me:

    SwingUtilities.invokeLater(() -> {
            JScrollBar bar = scroll.getVerticalScrollBar();
            bar.setValue(bar.getMaximum());
    });
    
    0 讨论(0)
提交回复
热议问题