wood burning stoves 2.0*
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
Author

regarding focus in swing

Thyagarajan Ramanujam
Greenhorn

Joined: Mar 24, 2008
Posts: 25
Hi

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);
userNameField.addFocusListener(this);
userNameField.setName("UserNameField");

passwordField = new JTextField(10);
passwordField.addFocusListener(this);
passwordField.setName("PasswordField");

mainPanel.add(userNameField);
mainPanel.add(passwordField);
frame = new JFrame("TableExample");
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
frame.setBounds(200, 200, 300, 300);
}
public static void main(String s[]) {
new NewClass();
}
public void focusGained(FocusEvent e) {
System.out.println(((JTextField)e.getSource()).getName());
}
public void focusLost(FocusEvent e) {
String text = ((JTextField)e.getSource()).getText();
if(!(text.equalsIgnoreCase(("Country"))))
userNameField.requestFocus(true);
}
}
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

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
Greenhorn

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?

InputVerifier
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: regarding focus in swing
 
Similar Threads
Is this is bug in jdk 1.5 ??
Focus Events
Issue with selection of text when textfield component gains focus.
keyboard action of my JButton
Creating and showing JFrame from another JFrame