I have created the buttons for on-screen keyboard. The only thing I don't know is how to add the corresponding letter/character via actionListener to the jTextField. I know if it was not jTextField I could use "append".

Dani AI

Generated

Short answer for : don’t rely on a manual string concat of getText()/setText() if you want proper caret/selection behavior. Two cleaner options are replaceSelection(...) (simple) or inserting into the field’s Document (more control). These work even when you need to insert at the current caret or replace a selection.

Example — insert whatever label is on the clicked button (keeps selection/caret semantics):

String key = ((JButton) e.getSource()).getText();
textField.replaceSelection(key);   // inserts at caret or replaces current selection

If you need to control the exact insertion position and update the caret explicitly, use the Document API:

String key = ((JButton) e.getSource()).getText();
int pos = textField.getCaretPosition();
try {
    textField.getDocument().insertString(pos, key, null);
    textField.setCaretPosition(pos + key.length());
} catch (BadLocationException ex) {
    // handle error
}

Practical tips / troubleshooting:

  • Clicking a JButton can move focus away from the JTextField. Either call textField.requestFocusInWindow() after inserting, or make the buttons non-focusable (button.setFocusable(false)) if that fits your UX (but consider accessibility).
  • ActionListeners run on the EDT, so UI updates are safe there; if you ever insert from a background thread, wrap changes in SwingUtilities.invokeLater.
  • If you’re using filters/formatters (e.g., DocumentFilter, JFormattedTextField) those may block/modify inserts — test with plain JTextField first.

This addresses the behavior you reported (single-letter replaces previous text) by inserting at the caret or replacing selection rather than blindly resetting the whole field. It builds on the earlier suggestions from and but uses APIs that preserve caret/selection and give predictable results.

Recommended Answers

All 5 Replies

You can use getText() to get the existing text in the text field, then append your new character, then use setText() to update the field.

then append your new character,

How?

You an use the two methods James gave you to accomplish that:

if(e.getSource() == aButton) {
    //get text already in your text field
    //add a to that
    //put text back in text field
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.