每次(第一次除外),我在JEditorPane中设置的文本滚动条都会跳到JEditorPane的底部。有什么办法可以避免这种情况?我尝试的一种方法是在setText()之后使用setCaretPosition(0)。它可以工作,但这并不是我真正需要的。滚动条向下跳然后向上跳。有没有一种方法可以避免settext()上滚动条的任何移动?
我的代码:
package test; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JEditorPane; import javax.swing.JScrollPane; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; public class Test extends JApplet implements HyperlinkListener { JEditorPane dataDisplayer = new JEditorPane(); public void init() { ataDisplayer.setEditable(false); dataDisplayer.add(new JButton()); dataDisplayer.setContentType("text/html"); JScrollPane jsp = new JScrollPane(dataDisplayer); dataDisplayer.setText("<a href=''>Change Text</a><br><br><br><br><br><br><br><br><br><br>bla"); this.dataDisplayer.addHyperlinkListener(this); setContentPane(jsp); } @Override public void hyperlinkUpdate(HyperlinkEvent arg0) { dataDisplayer.setText("<a href=''>Change Text</a><br><br><br><br><br><br><br><br><br><br>bla bla"); } }
有不同的方法可以做到这一点。一种方法是简单地避免插入符号可见性调整,如下所示:
import java.awt.Rectangle; import javax.swing.JButton; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.text.DefaultCaret; public class TestEditorPane implements HyperlinkListener { private final class MyCaret extends DefaultCaret { @Override protected void adjustVisibility(Rectangle nloc) { } } JEditorPane dataDisplayer = new JEditorPane(); private MyCaret caret; @Override public void hyperlinkUpdate(HyperlinkEvent arg0) { dataDisplayer.setText("<a href=''>Change Text</a><br><br><br><br><br><br><br><br><br><br>bla bla"); } public void init() { JFrame frame = new JFrame(); dataDisplayer.setEditable(false); caret = new MyCaret(); dataDisplayer.setCaret(caret); dataDisplayer.add(new JButton()); dataDisplayer.setContentType("text/html"); JScrollPane jsp = new JScrollPane(dataDisplayer); dataDisplayer.setText("<a href=''>Change Text</a><br><br><br><br><br><br><br><br><br><br>bla"); this.dataDisplayer.addHyperlinkListener(this); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setContentPane(jsp); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new TestEditorPane().init(); } }); } }