【问题标题】:JTextArea show Caret while setEditable is falseJTextArea 在 setEditable 为 false 时显示插入符号
【发布时间】:2011-11-06 18:50:37
【问题描述】:

当 setEditable 被禁用时,如何在 JTextArea 中添加插入符号?

需要让插入符号可见时的示例代码:

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 并接收到将在 TextArea 中显示的相应 InputStream。这很好用,但由于 setEditable(false),插入符号被隐藏了。

【问题讨论】:

  • 我只是测试您的代码(在 Windows 7 中),文本区域并没有按照您说的那样做...也许如果您添加更多代码,可能会更好地看到问题
  • 你说的OutputStream在哪里?抱歉,我没看准你的目标。
  • 这是一个示例代码,试图展示我如何构建 TextArea。此代码也可以看到问题,它运行带有 TextArea 的单个 Frame,禁用编辑并附加 String,这没关系,但 Caret 不可见,这就是我卡住的地方。
  • 好的。我觉得还有什么问题……那么,看两个答案。他们都工作。 @StanislavL 答案的第一行是目前最好的解决方案,简单而干净:)

标签: java swing jtextarea


【解决方案1】:

我尝试了 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);
    }
});

在上面的示例中,我决定即使离开文本区域也保持选择可见。

【讨论】:

    【解决方案2】:

    好吧,我在这里放了一个代码片段,它显示了插入符号,但不要让编辑 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);
    }
    

    请注意,用户可以移动插入符号,但他/她不能编辑文本

    【讨论】:

      【解决方案3】:

      text.getCaret().setVisible(true) 和/或text.getCaret().setSelectionVisible(true)

      【讨论】:

      • +1 它们都有效。我的解决方案是一个肮脏的把戏,那么最好使用你的:)
      猜你喜欢
      • 1970-01-01
      • 2013-05-21
      • 1970-01-01
      • 2011-08-22
      • 2013-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多