I'm writing an action for a jTextPane's getActionMap that when I type ')' IF at the Caret Position there's a ')' the action overwrite the symbol, ELSE it normally types ')'. This is the code:
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);
}
I can't understand why, even if the the boolean of the 'if' is true, it does not go in the if way. Can you help me?
even if the the boolean of the 'if' is true, it does not go in the if way
Did you do any basic debugging to see what is happening?
if (jTextPane1.getDocument.getText(position,1)== ")") {
The problem is you should NOT be using "==" for object comparison. It will never be true.
You should be using the equals(...)
method:
This is easily verified by simplifying the code and added debug statements.
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");
}
With the above simple code you can easily verify if the text value is what you expect. Don't write complex statements with multiple methods. Simplyfying the code into multiple statements makes it much easier to debug.