JTextArea show Caret while setEditable is false
How can I put Caret in JTextArea while setEditable is disabled?
A sample code when I need Caret to be visible:
public void run(){
JFrame frame = new JFrame();
JTextArea text = new JTextArea();
text.setEditable(false);
String line = "added line";
text.append(line);
text.setCaretPosition(text.getCaretPosition() + line.length());
frame.getContentPane().add(text);
frame.setSize(300,300);
frame.setVisible(true);
}
What I want to achieve is that, when the user types within TextArea, characters m开发者_JS百科ust not be displayed. Typed characters are redirected to OutputStream and appropriate InputStream is received which will be displayed within TextArea. This works fine, but Caret is hidden because of setEditable(false).
text.getCaret().setVisible(true)
and/or text.getCaret().setSelectionVisible(true)
Well, I put here a code fragment which shows the caret but don't let edit the JTextArea. I hope it helps you. It's a little trick which plays with the focus of the text area, when focus is gained, the edition is disabled; but when it's losed, the edition it's possible. In this way, the user is unable to edit it but can see the caret.
public void run() {
JFrame frame = new JFrame();
final JTextArea text = new JTextArea();
text.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent fe) {
text.setEditable(true);
}
public void focusGained(FocusEvent fe) {
text.setEditable(false);
}
});
text.setEditable(true);
String line = "added line";
text.append(line);
text.setCaretPosition(text.getCaretPosition() + line.length());
frame.getContentPane().add(text);
frame.setSize(300,300);
frame.setVisible(true);
}
Notice that the user can move the caret, but he/she can't edit the text
I tried the solution originally proposed by StanislavL. However, other issues emerged. For example, after leaving the JTextArea and focusing back later, the caret would turn invisible again.
I suspect that caret was not implemented as most people would expect to behave. While I saw some authors proposing to re-implement the caret, I successfully achieved visible caret behavior with following small listener:
textArea.getCaret().setVisible(true);
textArea.getCaret().setSelectionVisible(true);
textArea.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
textArea.getCaret().setVisible(true);
textArea.getCaret().setSelectionVisible(true);
}
@Override
public void focusLost(FocusEvent e) {
textArea.getCaret().setSelectionVisible(true);
}
});
On example above, I decided to keep the selection visible even if one leaves the text area.
精彩评论