我正在为 jTextPane 的 getActionMap 编写一个操作,当我键入 ')' 时,如果在插入符号位置有一个 ')' 操作会覆盖该符号,否则它通常会键入 ')'。 这是代码:
Action action1 = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
char bracket = ')';
try {
int position = jTextPane1.getCaretPosition();
if (jTextPane1.getDocument.getText(position,1)== ")") {
jTextPane1.getDocument().remove(position, 1);
jTextPane1.getDocument().insertString(position, ")", null);
} else {
jTextPane1.getDocument().insertString(position, ")", null);
}
} catch (Exception e1) {}
}
};
String key1 = "typed )";
jTextPane1.getInputMap().put(KeyStroke.getKeyStroke(key1), key1);
jTextPane1.getActionMap().put(key1, action1);
}
我不明白为什么,即使“if”的 boolean 值是true,它也不会按照if的方式进行。你能帮我吗?
最佳答案
even if the the boolean of the 'if' is true, it does not go in the if way
您是否进行了任何基本调试以查看发生了什么?
if (jTextPane1.getDocument.getText(position,1)== ")") {
问题是您不应该使用“==”进行对象比较。这永远不会是真的。
您应该使用equals(...)
方法:
通过简化代码和添加调试语句可以轻松验证这一点。
String text = jTextPane1.getDocument().getText(position, 1);
System.out.println(text);
if (text.equals(")"))
{
System.out.println("matches");
}
else
{
System.out.println("doesn't match");
}
通过上面的简单代码,您可以轻松验证文本值是否是您期望的值。不要使用多个方法编写复杂的语句。将代码简单地分解为多个语句使得调试变得更加容易。
关于java - 找出 jTextPane 中的某个位置是否有特定的字符 [java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36166769/