Read-only JTextComponent with caret
In Java, JTextComponent (such as JTextArea or JTextPane) can be set to read-only using JTextComponent.setEditable(false) which works fine but there is side effect – the caret is missing. Having the caret around in the read-only text component can be useful as the user can navigate around and use shift key to select the text using keyboard. Here is the code:
import javax.swing.plaf.UIResource;
import javax.swing.text.DefaultCaret;
/**
* This class is a copy of javax.swing.text.DefaultCaret I only change it to allow it to be display in the
* non-editable text component
*/
public class NonEditableTextComponentCaret extends DefaultCaret implements UIResource {
boolean blindOff = false;
/** Constructs a NonEditableTextComponent caret. */
public NonEditableTextComponentCaret() {
super();
final NonEditableTextComponentCaret This = this;
// Create a new one
(new Thread() {
/**{@inheritDoc}*/ @Override
public void run() {
while(true) {
try { Thread.sleep(500); }
catch(InterruptedException IE) { break; }
This.blindOff = !This.blindOff;
This.repaint();
}
}
}).start();
}
// Forcefully visible when the component owns the focus or the selection is being shown
/**{@inheritDoc}*/ @Override
public void setVisible(boolean isVisible) {
if(!isVisible && this.isSelectionVisible() && this.getComponent().isFocusOwner()) return;
super.setVisible(isVisible);
}
// The visibility of the caret depends on whether or not the selection is visible
/**{@inheritDoc}*/ @Override
public boolean isVisible() {
return this.isSelectionVisible() && this.blindOff;
}
}
The class NonEditableTextComponentCaret is very easy to use. Here is how:
JTextComponent TC = new JTextPane();
TC.setEditable(false);
TC.setCaret(new NonEditableTextComponentCaret());
Done! How easy.
Enjoy coding.
Categories: Computer, Java, Programming Tricks, Software Development Computer, Java Programming Trick, Java Swing


Recent Comments