Ryan Ryan - 2 months ago 6
Java Question

How to highlight text in a JTextPane with setFocusable(false)?

So I have a

JTextPane
that basically serves as a console. I have it in the center field of a
JFrame
and a
JTextField
in the south field. The
JTextField
will take the text it has, and add it to the
JTextPane
when the user presses enter. In order to make the
JTextPane
not editable by the user I had to
setFocusable(false)
, because using
setEditable(false)
stopped any text from appearing on the
JTextPane
. But while I don't want the user to edit the pane, I would still like the user to be able to highlight text in the pane, but I can't seem to find a way to do this.

Below is a sample demonstrating what I mean

Sample

package resources;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;

public class SampeTextPane extends JFrame
{
public SampeTextPane()
{
setPreferredSize(new Dimension(350, 200));
setDefaultCloseOperation(EXIT_ON_CLOSE);

JTextPane display = new JTextPane();
display.setBorder(new EmptyBorder(5, 5, 5, 5));
display.setMargin(new Insets(5, 5, 5, 5));
display.setFocusable(false);
appendToPane(display, "Example", Color.BLUE);

JTextField field = new JTextField();
field.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
appendToPane(display, field.getText(), Color.BLACK);
field.setText("");
}
});

add(display, BorderLayout.CENTER);
add(field, BorderLayout.SOUTH);

pack();
setVisible(true);
}

private void appendToPane(JTextPane pane, String text, Color color)
{
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, color);

aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);

int len = pane.getDocument().getLength();
pane.setCaretPosition(len);
pane.setCharacterAttributes(aset, false);
pane.replaceSelection(text + "\n");
}

public static void main(String[] args)
{
new SampeTextPane();
}
}


Thanks in advance for any help.

Answer

using setEditable(false) stopped any text from appearing on the JTextPane.

You can make the JTextPane uneditable but you can't update the text via the text pane.

Instead you can update the text via the Document:

//int len = pane.getDocument().getLength();
//pane.setCaretPosition(len);
//pane.setCharacterAttributes(aset, false);
//pane.replaceSelection(text + "\n");

try
{
    StyledDocument doc = pane.getStyledDocument();
    doc.insertString(doc.getLength(), text, aset);
}
catch(BadLocationException e) { System.out.println(e); }
Comments