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.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		frm.add(txt);
		frm.add(btn);
		frm.setSize(100,100);
		frm.setLayout(new FlowLayout());
		
		btn.addActionListener(new SimulateBckSpaceKeyWithButton());
		frm.setVisible(true);
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		txt.requestFocusInWindow();
		txt.setHighlighter(null);
		
		
		try {
			Robot robot = new Robot();
		    robot.keyPress(KeyEvent.VK_BACK_SPACE);
		    robot.keyRelease(KeyEvent.VK_BACK_SPACE);
		   
		} catch (AWTException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		

		
	}

}

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));

Edited 5 Years Ago by hfx642: n/a

Comments
Sweet
This article has been dead for over six months. Start a new discussion instead.