• Post Reply Bookmark Topic Watch Topic
  • New Topic

Text Cursor in a JTextField

 
Jamie Wool
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to know if there is a way to move the Text cursor to a desired JTextField if some event occurs, say for example a button being pressed in my application.
 
Lee George
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
java.awt.Component exposes the method requestFocus(boolean temporary) and as a superclass to JTextField you can access it. Set the temporary value to false. A quick example, consider a button that when clicked requests the focus to a JTextField.

public class swinger {
JTextField thisField;
JButton thisButton;

public swinger(){
thisField = new JTextField();
thisButton = new JButton();
init();
}

private void init(){
thisButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
thisField.requestFocus();
}
});
}
}

You must remember that this method only requests the focus, if for some reason the focus cannot be granted such as a message box has the focus and must be removed first then the requst will be remembered and when the message box is removed the foucs will be granted. Also, when the focus is granted a FOCUS_GAINED event is generated. I recommend you use this event before you perform any work on the field so you avois any errors.

Hope this helps.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!