Hot questions for Using JTextField in keyevent

Question:

How can I trigger backspace key press event when button click.

private void doClick(char type)
{
   jTextField1.dispatchEvent(new KeyEvent(jTextField1, KeyEvent.KEY_PRESSED, System.currentTimeMillis(),KeyEvent.SHIFT_DOWN_MASK, KeyEvent.VK_7, type));
   jTextField1.dispatchEvent(new KeyEvent(jTextField1, KeyEvent.KEY_TYPED, System.currentTimeMillis(),KeyEvent.SHIFT_DOWN_MASK, KeyEvent.VK_UNDEFINED, type));
   jTextField1.dispatchEvent(new KeyEvent(jTextField1, KeyEvent.KEY_RELEASED, System.currentTimeMillis(),KeyEvent.SHIFT_DOWN_MASK, KeyEvent.VK_7, type));
}

Im using this method to add one character when button click. Is there any mechanism to trigger backspace key press event like this.


Answer:

Okay, before I answer the question, because I believe the approach is dirty, here are two, similar, concepts...

You could make use of the Action API, which would allow you to define self-contained units for work. These could be abstract to do the heavy lifting, in the particular case of inserting new values, but this demonstrates the use case of removing a character...

public class BackspaceAction extends AbstractAction {

    private JTextField field;

    public BackspaceAction(JTextField field) {
        putValue(NAME, "Back-space");
        this.field = field;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String text = field.getText();
        if (!text.isEmpty()) {
            int position = field.getCaretPosition();
            if (position > 0) {
                text = text.substring(0, position - 1) + text.substring(position);
                field.setText(text);
                field.setCaretPosition(Math.max(position - 1, 0));
            }
        }
    }

}

Or through use the Document itself...

public class BackspaceAction extends AbstractAction {

    private JTextField field;

    public BackspaceAction(JTextField field) {
        putValue(NAME, "Back-space");
        this.field = field;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Document doc = field.getDocument();
        if (doc.getLength() > 0) {
            int position = field.getCaretPosition();
            if (position > 0) {
                try {
                    doc.remove(position - 1, 1);
                    field.setCaretPosition(Math.max(position - 1, 0));
                } catch (BadLocationException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

}

Which would simply instantiated using something like...

JButton back = new JButton(new BackspaceAction(field));

If you're hell bent on trying to get into the nitty gritty low layers of the API, then something like....

char value = (char)8;
field.dispatchEvent(new KeyEvent(field, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, KeyEvent.VK_BACK_SPACE, value));
field.dispatchEvent(new KeyEvent(field, KeyEvent.KEY_RELEASED, System.currentTimeMillis(), 0, KeyEvent.VK_BACK_SPACE, value));
field.dispatchEvent(new KeyEvent(field, KeyEvent.KEY_TYPED, System.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, value));

might work. I say might, as this does work on Windows 7, but I make no guarantee if it will work on any other platforms or versions of Windows

Now, for me, I can look at the other two Actions and see what they are trying to do, I look at the key event approach and begin to scratch my head wondering why, but that's just me...

Question:

I'm developing a game and I have a JFrame that receives in input the player name in a JTextField.

What I want is the possibility to close the window by either pressing a JButton or by pressing the ENTER key.

When the window opens the JTextField must have the focus (the cursor should appear in the component).

I already saw:

How do you make key bindings for a java.awt.Frame?

How do you make key binding for a JFrame no matter what JComponent is in focus?

but I have not solved the problem, there's probably something wrong in the focus management.

I tried the following code:

public class PlayerNameWindow extends JFrame implements KeyListener {

    private String playerName;
    private JLabel backgroundLabel;
    private JLabel enterNameLabel;
    private JButton confirmButton;
    private JTextField nameField;
    private Image background;

    public PlayerNameWindow() {

        initComponents();

    }

    private void initComponents() {

        backgroundLabel = new JLabel();
        enterNameLabel = new JLabel();
        confirmButton = new JButton();
        nameField = new JTextField();

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 200));
        setResizable(false);
        getContentPane().setLayout(null);

        addKeyListener(this);

        enterNameLabel.setFont(new Font("Tahoma", 1, 18)); 
        enterNameLabel.setForeground(new Color(255, 255, 255));
        enterNameLabel.setText("Enter your name:");
        getContentPane().add(enterNameLabel);
        enterNameLabel.setBounds(40, 80, 160, 30);

        confirmButton.setText("Confirm");
        confirmButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent evt) {
                confirmButtonMouseClicked(evt);
           }
        });
        confirmButton.setBounds(160, 150, 90, 25);
        getContentPane().add(confirmButton);

        getContentPane().add(nameField);
        nameField.setBounds(220, 80, 140, 30);

        getContentPane().add(backgroundLabel);
        backgroundLabel.setBounds(0, 0, 400, 200);

        pack();
        setLocationRelativeTo(null); 

    }                      

    private void confirmButtonMouseClicked(MouseEvent evt) { 

        confirmAction();

    }         

    private void confirmAction() {

        playerName = nameField.getText();
        System.exit(0);

    }

    public String getPlayerName() {

          return this.playerName;

    }

    public void keyPressed(KeyEvent e) {

         int code = e.getKeyCode();
         if (code == KeyEvent.VK_ENTER)
             System.exit(0);

    }

    public void keyReleased(KeyEvent e) {

           //do-nothing

    }

    public void keyTyped(KeyEvent e) {

          //do-nothing

    }

}

How can I do?

Thanks


Answer:

add keyListener to the JTextField. in your code, nameField.addKeyListener(this);

Question:

I'm writing a CashRegister program and I'm currently working on the CashierView where I have added an option for the Cashier to input the amount of cash received by the customer. I now formatted it so that the user only can input numbers and 1 period. I now want to limit the numbers you can input after the period to two. I'm struggling to make this work.

I commented out one of the codes that I tried, but didn't work, incase it might be interesting.

Appreciate all the help! Br, Victor

    private void jCashReceivedKeyTyped(java.awt.event.KeyEvent evt) {                                       
    char c = evt.getKeyChar(); //Allows input of only Numbers and periods in the textfield
    //boolean tail = false;
    if ((Character.isDigit(c) || (c == KeyEvent.VK_BACKSPACE) || c == KeyEvent.VK_PERIOD)) {        
        int period = 0;  
        if (c == KeyEvent.VK_PERIOD) { //Allows only one period to be added to the textfield
            //tail = false;
            String s = getTextFieldCash();
            int dot = s.indexOf(".");
            period = dot;
            if (dot != -1) {
                evt.consume();
            }
        }
       //. if (tail=true){  //This is the code that I tried to use to limit  input after the period to two

           // String x = getTextFieldCashTail();
          //  if (x.length()>1){
             //   evt.consume();
         //   }
       // }
    } 
    else {
        evt.consume();
    }
}  

Answer:

If you're dead set on doing this with a KeyEvent, here's one possible method:

private void jCashReceivedKeyTyped(java.awt.event.KeyEvent evt) {
    char c = evt.getKeyChar(); //Allows input of only Numbers and periods in the textfield
    if ((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || c == KeyEvent.VK_PERIOD)) {
        String s = getTextFieldCash();
        int dot = s.indexOf(".");
        if(dot != -1 && c == KeyEvent.VK_PERIOD) {
            evt.consume();
        } else if(dot != -1 && c != KeyEvent.VK_BACK_SPACE){
            String afterDecimal = s.substring(dot + 1);
            if (afterDecimal.length() > 2) {
                evt.consume();
            }
        }
    }
}

Hope this helps. Just keep in mind that by listening to a KeyEvent, if someone copies and pastes values into your JTextField, this won't catch that. If you want to catch any possible type of input, you'll want to use a DocumentListener. If you're wondering how to use a DocumentListener, here is some code that shows how to use it on a JTextField.

Question:

I am trying to add a keyListener to my JTextField. From what i see every one is using getKeyCode() method for the KeyEvent. I keep getting the error in Eclipse that

The method getKeyCode() is undefined for the type KeyEvent*

What did I do Wrong?...

Here is my code:

TF_Message.addKeyListener(new KeyAdapter() 
{
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER)
        {
            ACTION_B_SEND();
        }
    }
});

Answer:

Don't use a KeyListener.

A JTextField is designed to be used with an ActionListener:

textField.addActionListener(...);

The ActionListener will be invoked when the Enter key is pressed.

ACTION_B_SEND();

Also, methods should NOT start with an upper case character. Learn by example from the Java API and don't make up your own conventions.

Same with variable names. They should NOT start with an upper case character.