How to Write Backspace code for textfield in java application?

This is my simple button what code I have to write to make it a backspace button.

        JButton btnBackspace = new JButton("B");
        btnBackspace.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {

                }
            }
        });
        btnBackspace.setFont(new Font("Tahoma", Font.BOLD, 22));
        btnBackspace.setForeground(Color.BLACK);
        Image btBack = new 
        ImageIcon(this.getClass().getResource("/b.png")).getImage();
        btnBackspace.setIcon(new ImageIcon(btBack));
        btnBackspace.setBounds(121, 145, 97, 63);
        frame.getContentPane().add(btnBackspace);;

Answer

This is a sample code of a backspace button that will erase text from the assigned text field here -> first the text is saved into backspace variable the according to the length of text -1 is done to erase the text and then text is assigned to base textfeild again

JButton btnBackspace = new JButton("uF0E7");
        btnBackspace.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String backspace = null;
                if(txtResult.getText().length()>0) {
                    StringBuilder strBuilder = new StringBuilder(txtResult.getText());
                    strBuilder.deleteCharAt(txtResult.getText().length()-1);
                    backspace = strBuilder.toString();
                    txtResult.setText(backspace);
                }
            }
        });
        btnBackspace.setFont(new Font("Wingdings", Font.BOLD, 22));
        btnBackspace.setForeground(Color.BLACK);
        Image btBack = new ImageIcon(this.getClass().getResource("/b.png")).getImage();
        btnBackspace.setIcon(new ImageIcon(btBack));
        btnBackspace.setBounds(121, 145, 97, 63);
        frame.getContentPane().add(btnBackspace);

Leave a Reply

Your email address will not be published. Required fields are marked *