JScrollPane scrollbar jumps down on JEditorPane.setText()

前端 未结 2 902
青春惊慌失措
青春惊慌失措 2021-01-15 14:47

Every time (except first time) I set text in JEditorPane scrollbar jumps to the bottom of JEditorPane. Is there any way to avoid this? One way that I tried is to use setCare

2条回答
  •  花落未央
    2021-01-15 15:41

    There are different ways to go with that. One would be to simply avoid caret visibility adjustement, like this:

    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("Change Text









    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("Change Text









    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(); } }); } }

提交回复
热议问题