简体   繁体   English

不可编辑时,将插入符号保留在TextArea中

[英]Keep caret in TextArea when non-editable

I'm using java, and I'm trying to make a JTextArea that is non-editable but still has the caret in the field. 我正在使用java,我正在尝试创建一个不可编辑的JTextArea但仍然在该字段中有插入符号。 In other words, a Text Area that does not display characters typed by the user, but still has the blinking caret (ie focus). 换句话说,文本区域不显示用户键入的字符,但仍具有闪烁的插入符号(即焦点)。

I honestly stumped on this problem. 老实说,我很难过这个问题。 I've tried mucking around with setEditable , but theres no way to keep the caret. 我试过用setEditable解决setEditable ,但是没有办法保留插入符号。 I've also tried deleting the character the user enters as soon as they type it, but i can't stop it flashing on the screen. 我也尝试删除用户输入的字符,但我无法阻止它在屏幕上闪烁。

I think the following will help you: 我认为以下内容对您有所帮助:

textArea.getCaret().setVisible(true);

or 要么

textArea.getCaret().setSelectionVisible(true);

As for the answers above 至于上面的答案

textArea.getCaret().setVisible(true);

does not always work perfectly, if the TextArea or EditorPane loses focus, say you click on a different frame or something, when you come back the cursor will be invisible again. 并不总是完美地工作,如果TextArea或EditorPane失去焦点,比如你点击不同的框架什么的,当你回来时光标将再次不可见。

I have had the same issues, it appears the solution is to add a focus listener and set it visible every time the editor gains focus. 我遇到了同样的问题,似乎解决方案是添加一个焦点监听器,并在每次编辑器获得焦点时将其设置为可见。

text.addFocusListener(new FocusAdapter() {
  @Override
  public void focusGained(FocusEvent e) {
    text.getCaret().setVisible(true); // show the caret anyway
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM