JScrollPane scrollbar jumps down on JEditorPane.setText()

前端 未结 2 901
青春惊慌失措
青春惊慌失措 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:16

    The following solved the problem for me, after 50 minutes of despair:

    JEditorPane.grabFocus();
    JEditorPane.setCaretPosition(20);
    
    0 讨论(0)
  • 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("<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();
                }
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题