注意:我正在重新询问this问题,因为我需要一个答案,答案中的链接已断开。
我正在编写一个简单的聊天程序作为学校项目的一部分,我希望用户能够自动跟踪消息,如果它们位于底部,但不会因为不得不再次向上滚动而烦恼如果他们正在寻找更高的东西。目前,无论如何,我的代码都只是滚动到底部。基本代码如下,我真的不知道如何将其转换为SSCCE。如果有人可以,请随意这样做。
JTextArea jta = new JTextArea(50, 50);
JScrollPane scroll = new JScrollPane(jta);
try {
int iter = 0;
while (true) { //Not a for loop because it should not end after x iterations
Thread.sleep(500);
jta.append("Test text #" + iter);
iter++;
//Check if they are at the bottom and if so scroll down to the new bottom.
}
} catch (InterruptedException ex) {
System.out.println("Error!");
}
答案 0 :(得分:3)
不确定这是最好的方法,但是这里有一些代码会在用户向上滚动时停止向下滚动。当他滚动回到底部时,会再次开始自动滚动。
这个想法是通过比较textarea的高度和滚动窗格的可见矩形的位置和高度来检查用户是否向上移动。如果匹配,则表示滚动位于底部,用户想要自动滚动。在另一种情况下,我们然后每次textarea更改时强制可见矩形保持不变。
小SSCCE:
import java.awt.BorderLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class TestScrollbars {
protected void initUI() {
final JFrame frame = new JFrame();
frame.setTitle(TestScrollbars.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextArea chat = new JTextArea(10, 40);
chat.setLineWrap(true);
chat.setEditable(false);
chat.setWrapStyleWord(false);
final JScrollPane scrollPane = new JScrollPane(chat);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
frame.setLayout(new BorderLayout());
frame.add(scrollPane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
Timer t = new Timer(200, new ActionListener() {
private int i = 1;
@Override
public void actionPerformed(ActionEvent e) {
final Rectangle visibleRect = chat.getVisibleRect();
boolean scroll = chat.getHeight() <= visibleRect.y + visibleRect.height;
chat.append("Hello line " + i++ + "\n");
if (!scroll) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
chat.scrollRectToVisible(visibleRect);
}
});
}
}
});
t.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestScrollbars().initUI();
}
});
}
}
答案 1 :(得分:2)
编辑:
我将以下代码替换为更灵活的版本,该版本可用于JScrollPane中的任何组件。退房:Smart Scrolling。
以下是包含JTextArea或JTextPane的任何滚动窗格可以使用的一些可重用代码:
import java.awt.*;
import java.awt.event.*;
import java.util.Date;
import javax.swing.*;
import javax.swing.text.*;
public class ScrollControl implements AdjustmentListener
{
private JScrollBar scrollBar;
private JTextComponent textComponent;
private int previousExtent = -1;
public ScrollControl(JScrollPane scrollPane)
{
Component view = scrollPane.getViewport().getView();
if (! (view instanceof JTextComponent))
throw new IllegalArgumentException("Scrollpane must contain a JTextComponent");
textComponent = (JTextComponent)view;
scrollBar = scrollPane.getVerticalScrollBar();
scrollBar.addAdjustmentListener( this );
}
@Override
public void adjustmentValueChanged(final AdjustmentEvent e)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
checkScrollBar(e);
}
});
}
private void checkScrollBar(AdjustmentEvent e)
{
// The scroll bar model contains information needed to determine the
// caret update policy.
JScrollBar scrollBar = (JScrollBar)e.getSource();
BoundedRangeModel model = scrollBar.getModel();
int value = model.getValue();
int extent = model.getExtent();
int maximum = model.getMaximum();
DefaultCaret caret = (DefaultCaret)textComponent.getCaret();
// When the size of the viewport changes there is no need to change the
// caret update policy.
if (previousExtent != extent)
{
// When the height of a scrollpane is decreased the scrollbar is
// moved up from the bottom for some reason. Reposition the
// scrollbar at the bottom
if (extent < previousExtent
&& caret.getUpdatePolicy() == DefaultCaret.UPDATE_WHEN_ON_EDT)
{
scrollBar.setValue( maximum );
}
previousExtent = extent;
return;
}
// Text components will not scroll to the bottom of a scroll pane when
// a bottom inset is used. Therefore the location of the scrollbar,
// the height of the viewport, and the bottom inset value must be
// considered when determining if the scrollbar is at the bottom.
int bottom = textComponent.getInsets().bottom;
if (value + extent + bottom < maximum)
{
if (caret.getUpdatePolicy() != DefaultCaret.NEVER_UPDATE)
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
}
else
{
if (caret.getUpdatePolicy() != DefaultCaret.UPDATE_WHEN_ON_EDT)
{
caret.setDot(textComponent.getDocument().getLength());
caret.setUpdatePolicy(DefaultCaret.UPDATE_WHEN_ON_EDT);
}
}
}
private static void createAndShowUI()
{
JPanel center = new JPanel( new GridLayout(1, 2) );
String text = "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n";
final JTextArea textArea = new JTextArea();
textArea.setText( text );
textArea.setEditable( false );
center.add( createScrollPane( textArea ) );
System.out.println(textArea.getInsets());
final JTextPane textPane = new JTextPane();
textPane.setText( text );
textPane.setEditable( false );
center.add( createScrollPane( textPane ) );
textPane.setMargin( new Insets(5, 3, 7, 3) );
System.out.println(textPane.getInsets());
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(center, BorderLayout.CENTER);
frame.setSize(500, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer timer = new Timer(2000, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
Date now = new Date();
textArea.getDocument().insertString(textArea.getDocument().getLength(), "\n" + now.toString(), null);
textPane.getDocument().insertString(textPane.getDocument().getLength(), "\n" + now.toString(), null);
}
catch (BadLocationException e1) {}
}
});
timer.start();
}
private static JComponent createScrollPane(JComponent component)
{
JScrollPane scrollPane = new JScrollPane(component);
new ScrollControl( scrollPane );
return scrollPane;
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
编辑:
更新了代码,以便在滚动窗格的高度降低时也能正常工作。出于某种原因,默认行为是将滚动条向上移动一行,这意味着添加新文本时滚动条将不再保留在底部。
答案 2 :(得分:0)
旧的Apple MacOS方式可能有(几个)自动拆分窗格,可能会从下方向上撕裂,然后再次掉落。
他们会在同一个StyledDocument上创建多个视图(文本框),其中只有底部会自动滚动。