如何设置滚动到顶部-Jscrollpane中具有多个JTextareas的JPanel [英] How to set scroll to the top - JPanel that has multiple JTextareas inside Jscrollpane

查看:183
本文介绍了如何设置滚动到顶部-Jscrollpane中具有多个JTextareas的JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JScrollPane中有一个JPanel. JPanel垂直包含多个JTextArea.

I have a JPanel in a JScrollPane. The JPanel contains multiple JTextAreas vertically.

每当刷新页面时,我都希望将滚动窗格的滚动保持在顶部. 当前,滚动始终从底部开始.

I like to keep the scroll of the scrollpane to the top whenever the page is refreshed. Currently, the scroll always starts from the bottom.

这是我当前的代码,它不起作用.

this is my current code and it doesn't work..

    panel.invalidate();
    panel.revalidate();
    panel.repaint();
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            ((JPanel) panel).setLocation(new Point(0, 0));
        }
    });

我也尝试过将下面的代码添加到滚动窗格中,但这不起作用.

I've also tried adding this code below to scrollpane, but it doesn't work..

scrollPanel.getViewport().setViewPosition( new Point(0, 0) );

我研究了其他stackoverflow问题,他们在Jscrollpane中使用了Jtextarea(他们使用setCaretPosition(0)解决了问题,但是我无法在面板上使用相同的功能).就我而言,有一个额外的层.

I've looked into other stackoverflow questions and they use Jtextarea inside Jscrollpane (they solved it using setCaretPosition(0), however I can't use the same function to the panel). In my case, there is an extra layer.

我该如何解决..?

编辑**

根据Pavlo Viazovskyy的建议,我也在下面进行了尝试,但它仍然对我不起作用..:(

Based on advice from Pavlo Viazovskyy, I've also tried this below and it still doesn't work for me.. :(

    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            scrollPane.getVerticalScrollBar().setValue(0);
        }
    });

推荐答案

非常感谢您的所有评论. 抱歉,我没有在问题中给出完整的适当示例,因为涉及的类太多了.

Thank you very much for all the comments. sorry I didn't give a full proper example in the question as there were too many different classes involved..

在我的情况下,在ScrollPane内的Panel内部的textareas中,默认情况下,我通过使用invokeViewer方法中的setViewPosition方法对scrollPane进行滚动到顶部.

In my case, textareas inside Panel inside ScrollPane, I made the scroll to the top by default by using setViewPosition method to scrollPane in the invokelater method.

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        scrollPane.getViewport().setViewPosition( new Point(0, 0) );
    }
});

这篇关于如何设置滚动到顶部-Jscrollpane中具有多个JTextareas的JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆