Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java JTextPane auto-scroll stops working after selecting text

So this issue has been bugging me for a long time now, and it effectively renders my game unplayable if it is triggered. The situation is that I have four items in my GUI:

private JPanel panel;
private JTextPane content;
private JScrollPane scroll;
private JTextField input;

The whole thing is setup in a BorderLayout, with a caret update policy that automatically scrolls the screen whenever text reaches the bottom. However, if I select any text in the JTextPane, all of a sudden the autoscroll stops working, and any new text added to the pane remains invisible until the user manually scrolls the scrollbar. I've attempted reapplying the caret update policy every time text is appended but that didn't work. I haven't a clue how to fix this, and attempts to google the problem have been fruitless. For reference, here is the relevant code from the constructor:

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(width, height);
setResizable(false);
panel = new JPanel();

input = new JTextField(30);
input.setBackground(Color.BLACK);
input.setForeground(Color.GREEN);
input.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, width / 40));
input.addActionListener(this);

content = new JTextPane();
scroll = new JScrollPane(content);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setPreferredSize(new Dimension(width, height - 80));
scroll.setMinimumSize(new Dimension(640, 480));
scroll.setBorder(null);

content.setBackground(Color.BLACK);
content.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, width / 40));
content.setEditable(false);

DefaultCaret caret = (DefaultCaret) content.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

panel.setLayout(new BorderLayout());
panel.add(scroll, BorderLayout.NORTH);
panel.add(input, BorderLayout.SOUTH);
panel.setBackground(Color.BLACK);

getContentPane().add(panel);

setVisible(true);

Is there a possible solution to this, or is this a limitation of Java AWT?

like image 552
Peter Davidson Avatar asked Apr 07 '26 21:04

Peter Davidson


1 Answers

I've attempted reapplying the caret update policy every time text is appended but that didn't work.

You also need to reset the caret to the end of the Document:

textPane.getDocument().insertString(...);
textPane.setCaretPosition(textArea.getDocument().getLength());
like image 95
camickr Avatar answered Apr 10 '26 11:04

camickr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!