File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes regarding focus in swing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "regarding focus in swing" Watch "regarding focus in swing" New topic

regarding focus in swing

Thyagarajan Ramanujam

Joined: Mar 24, 2008
Posts: 25

I have two JTextFields and FocusListener is added to both the field. When the first field loses focus, I am checking the contents of the first field.

If the text contains other than "Country", then the focus is set back to the first field.

I am getting the correct functionality but the focus is set to the second field and then it is set to first field.

What can be done to stop the second field getting focus in case to wrong entry?

I have also pasted the code
Thanks. Any help is appreciated.

//All classes are imported
public class NewClass implements FocusListener{

JFrame frame;
JTextField userNameField;
JTextField passwordField;
JPanel mainPanel;

public NewClass() {
mainPanel = new JPanel();

userNameField = new JTextField(10);

passwordField = new JTextField(10);

frame = new JFrame("TableExample");
frame.setBounds(200, 200, 300, 300);
public static void main(String s[]) {
new NewClass();
public void focusGained(FocusEvent e) {
public void focusLost(FocusEvent e) {
String text = ((JTextField)e.getSource()).getText();
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15302

It works fine for me, or, at least as you are expecting it to work. I don't see the password text field ever gain focus unless Country is typed into the username field. I am running Java 1.6.0_10 Beta on Ubuntu.

GenRocket - Experts at Building Test Data
Thyagarajan Ramanujam

Joined: Mar 24, 2008
Posts: 25
The password field does not gets focus. But if you see the console, it will be shown that the pasword field got focus and then the focus will be set back to the userfield.
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
> What can be done to stop the second field getting focus in case to wrong entry?

I agree. Here's the link:
subject: regarding focus in swing
It's not a secret anymore!