如何在禁用setEditable的情况下将插入符号放入JTextArea?
当我需要Caret可见时的示例代码:
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);
}
我想要实现的是,当用户在TextArea中键入时,字符一定不能显示。键入的字符被重定向到OutputStream,并收到相应的InputStream,该are将显示在TextArea中。这可以很好地工作,但是因为setEditable(false)而隐藏了插入符号。
发布于 2011-08-30 13:12:04
text.getCaret().setVisible(true)
和/或text.getCaret().setSelectionVisible(true)
发布于 2011-08-30 13:12:47
好吧,我在这里放了一个代码片段,它显示了插入符号,但不允许编辑JTextArea。我希望它能对你有所帮助。这是一个小把戏,用来处理文本区域的焦点,当焦点获得时,版本将被禁用;但当焦点丢失时,版本可能会被禁用。这样,用户就无法对其进行编辑,但可以看到插入符号。
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);
}
请注意,用户可以移动插入符号,但不能编辑文本
发布于 2019-05-13 13:49:31
我尝试了最初由StanislavL提出的解决方案。然而,也出现了其他问题。例如,在离开JTextArea并稍后重新聚焦后,插入符号将再次变为不可见。
我怀疑插入符号并没有像大多数人期望的那样实现。虽然我看到一些作者提议重新实现插入符号,但我通过下面的小侦听器成功地实现了可见的插入符号行为:
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);
}
});
在上面的示例中,我决定即使离开文本区也保持选择可见。
https://stackoverflow.com/questions/7243339
复制