我在JScrollPane(logScrollPane)元素中有JTextPane(log)。日志的内容设置为“text / html”。
我创建了一个附加此日志的方法,如下所示:
public void appendLog(String someHTMLText)
{
HTMLDocument doc = (HTMLDocument) log.getDocument();
HTMLEditorKit editorKit = (HTMLEditorKit) log.getEditorKit();
try
{
editorKit.insertHTML(doc, doc.getLength(), someHTMLText, 0, 0, null);
}
catch (BadLocationException | IOException ex)
{
// handle exceptions
}
}
我想改进此方法,并根据附加的布尔参数强制logScrollPane的VerticalScrollBar为move_to_the_bottom / stay_at_it's_position。 最终方法应如下所示:
public void appendLog(String someHTMLText, boolean scroll)
{
if(scroll)
{
/*
* append log and set VerticalScrollBar to the bottom by
* log.setCaretPosition(log.getDocument().getLength());
*/
}
else
{
// append log BUT make VerticalScrollBar stay at it's previous position
}
}
有什么建议吗? :)
答案 0 :(得分:0)
这与我想要实现的目标类似。关键是要改变scrollRectToVisible
的行为。
public class Docker extends JFrame {
boolean dockScrollbar = true;
MYTextPane textPane = new MYTextPane();
JScrollPane sp = new JScrollPane(textPane);
Docker() {
JCheckBox scrollbarDockCB = new JCheckBox("Dock scrollbar");
scrollbarDockCB.addItemListener(new DockScrollbarListener());
scrollbarDockCB.setSelected(true);
JButton insertText = new JButton("Insert text");
insertText.addActionListener(new TextInserter());
getContentPane().add(insertText, BorderLayout.PAGE_START);
getContentPane().add(sp);
getContentPane().add(scrollbarDockCB, BorderLayout.PAGE_END);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
class MYTextPane extends JTextPane {
MYTextPane() {
setEditorKit(new HTMLEditorKit());
}
@Override
public void scrollRectToVisible(Rectangle aRect) {
if (dockScrollbar)
super.scrollRectToVisible(aRect);
}
void insertText(String msg) {
HTMLEditorKit kit = (HTMLEditorKit) getEditorKit();
HTMLDocument doc = (HTMLDocument) getDocument();
try {
kit.insertHTML(doc, doc.getLength(), msg, 0, 0, null);
} catch (BadLocationException | IOException e1) {
e1.printStackTrace();
}
setCaretPosition(doc.getLength());
}
}
class TextInserter implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
textPane.insertText("AAA\n");
}
}
class DockScrollbarListener implements ItemListener {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
dockScrollbar = true;
JScrollBar sb = sp.getVerticalScrollBar();
sb.setValue(sb.getMaximum());
}
else if (e.getStateChange() == ItemEvent.DESELECTED)
dockScrollbar = false;
}
}
public static void main(String[] args) {
new Docker();
}
}
备注强>:
boolean dockScrollbar
作为文本窗格的字段,因为我有多个。JScrollPane
的字段,我在文本窗格中显示。答案 1 :(得分:0)
我从来没有在JEditorPane上尝试过,但您应该可以使用caret update policy
来控制它。
查看Text Area Scrolling了解详情。