java JScrollPane 设置滚动位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13213030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:53:58  来源:igfitidea点击:

JScrollPane Set Scroll Position

javaswingjscrollpanejscrollbaradjustment

提问by aditya parikh

I have following code snippet

我有以下代码片段

query_area = new JTextArea("");
query_scroll_pane = new JScrollPane(query_area);
query_scroll_pane.setSize(1000,80);
query_scroll_pane.setLocation(10,10);
query_panel.add(query_scroll_pane);

which adds my textarea to scrollpane. Now in a method i dynamically set text for the textarea as

它将我的 textarea 添加到滚动窗格。现在在一种方法中,我将 textarea 的文本动态设置为

sf.query_area.setText("Query "+(sf.query_counter)+sf.query_store[sf.query_counter]);
System.out.println("Position: "+sf.query_scroll_pane.getHorizontalScrollBar().getValue());

Now my query is when longer text is displayed, scrollbars appear but system.out.println prints position of scrollbar as 0 and not some increased value.

现在我的查询是当显示更长的文本时,滚动条出现但 system.out.println 将滚动条的位置打印为 0 而不是一些增加的值。

Why so ??

为什么这样 ??

回答by MadProgrammer

The only reason I can think of is because the view port position hasn't changed.

我能想到的唯一原因是视口位置没有改变。

The first thing that comes to mind, is the view port may not have yet reacted to a change in position from the text begin set, so dumping the result immediately after you've set the text is reflecting the current state of the scroll bar (which has not yet begin updated)

首先想到的是,视口可能尚未对文本开始设置的位置变化做出反应,因此在设置文本后立即转储结果反映了滚动条的当前状态(尚未开始更新)

You could try

你可以试试

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        System.out.println("Position: "+sf.query_scroll_pane.getHorizontalScrollBar().getValue());        
    }
});

instead and see if that prints out a more up-to-date value

相反,看看它是否打印出更新的值

Alternativly, you could add a AdjustmentListenerto the scroll bar, which will notify when changes occur JScrollBar#addAdjustmentListener

或者,您可以AdjustmentListener向滚动条添加一个,它会在发生更改时通知JScrollBar#addAdjustmentListener

回答by mKorbel

Now my query is when longer text is displayed, scrollbars appear but system.out.println prints position of scrollbar as 0 and not some increased value.

现在我的查询是当显示更长的文本时,滚动条出现但 system.out.println 将滚动条的位置打印为 0 而不是一些增加的值。

use

利用

query_area = new JTextArea();
DefaultCaret caret = (DefaultCaret) query_area.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);