How to perform an action when only first key pressed?

379 views Asked by At

I want a JTextFeild event when keyboard button pressed.I want concatenate "ADZ" text to the front whole text.(If we enter "2" whole text should be "ADZ2") THe Action will performed only first key press.After any key pressing action won't be performed.Action will performed only once. I tried below code,but if type 22 it gives"ADZADZ22".

private void JTextFeild1KeyTyped(java.awt.event.KeyEvent evt) {
String num1 = JTextFeild1.getText();
JTextFeild1.setText("ADZ"+num1);

I want this if type 22, it will gives ADZ22.

3

There are 3 answers

1
bvdb On BEST ANSWER

A simple way to solve it, is to check if the prefix is already there. This avoids that the same prefix is added twice.

private void JTextFeild1KeyTyped(java.awt.event.KeyEvent evt) {
  String num1 = JTextFeild1.getText();
  if (!num1.startsWith("ADZ"))
  {
    num1 = "ADZ" + num1;
    JTextFeild1.setText(num1);
  }
  ...
}

Please note: Java coding rules would suggest to make field names (e.g. jTextField) start with a lower case character. The same goes for method names (e.g. private void jTextField1KeyTyped)

1
Prashant On
public static int counter = 0;

Maintain a static counter at class level. At key press increase it by one. check :

    if(counter == 1) {
// do your operation
}
2
dly On

Check if your JTextField is empty and then set a prefix. This method sets "ADZ" when the field is empty and you type something and then appends everything you type.

public void keyTyped(KeyEvent ke) {
            if(txfInput.getText().equals("")) {
                txfInput.setText("ADZ");
            }
        }