I've created a JButton and a Jtextfield in java swing. I want the button to perform the same function as BackSpace key of the keyboard. Is there any means to assign the properties of the the BckSpace key to the button, i.e. inheriting the properties of the key.

What you can do is assign the button an ActionListener so that every time it is pressed it uses the Robot class to press the backspace key. You have to keep in mind that once you press the button the focus will switch from the text field to the button so once the actionPerformed method from the ActionListener interface starts you should switch the focus back to the text field and then simulate the backspace key being pressed.

Thanks for ur replies.

Here, I've written the code but when i click the button all the text are deleted.
I've also attached the .jar file.

import java.awt.AWTException;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

import java.awt.Robot;
public class SimulateBckSpaceKeyWithButton implements ActionListener{

	static JTextField txt = new JTextField(5);
	static JButton btn =  new JButton("BackSpace");
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		JFrame frm = new JFrame();
		frm.setLayout(new FlowLayout());
		btn.addActionListener(new SimulateBckSpaceKeyWithButton());

	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		try {
			Robot robot = new Robot();
		} catch (AWTException e1) {
			// TODO Auto-generated catch block


Member Avatar

That seems like a lot of work to me.
Put an actionListener on your button, and add the code...

myfield.setText (myfield.getText ().substring (0, myfield.getText ().length () - 1));
commented: Sweet +0