【问题标题】:JTextArea doesn't set the text indicator on the right before start typingJTextArea 在开始输入之前没有在右侧设置文本指示符
【发布时间】:2021-11-10 08:25:50
【问题描述】:

我在这里遇到的唯一问题是,在我开始输入之前,文本指示器始终显示在左侧。

输入前:

输入后:

JTextArea textArea = new JTextArea();
textArea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JScrollPane scroll = new JScrollPane(textArea);
scroll.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

这里是完整的代码:

import java.awt.ComponentOrientation;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Test extends JFrame {
    
    public Test() {
        this.setSize(300, 100);
        
        JTextArea textArea = new JTextArea();
        textArea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        JScrollPane scroll = new JScrollPane(textArea);
        scroll.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        
        scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        this.add(scroll);
        this.setVisible(true);
    }

}

顺便说一句,我在 Windows 10 上使用 Java 11。

【问题讨论】:

  • 我试验了你的代码。每次我暂停打字时,光标都会跳到该行的最左侧位置。当我继续打字时,光标又回到了右边。在我输入非空格字符之前,GUI 上不会显示空格。 setCaretPosition 方法只有在基础 Document 中至少有一个字符时才会起作用。有趣。
  • 你使用的是什么操作系统?
  • Windows 10; Java 14.0.2 编译为 Java 8 标准。

标签: java swing jtextarea


【解决方案1】:

这似乎对我有用(在 Windows 上测试)。

textArea.append("1");
textArea.setText("");

这有点老套,但正如你所说。不写任何内容,插入符号默认位于左侧。

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。
  • 即使在setVisible(true)之前添加它也会起作用。
  • 这个技巧只在 JTextArea 为空时有效。键入一个句子,用句号结束​​句子。注意光标和句点在 JTextArea 中的显示位置。
猜你喜欢
  • 1970-01-01
  • 2011-09-17
  • 1970-01-01
  • 2014-03-30
  • 2023-02-21
  • 2019-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多