This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

regarding focus in swing

 
Thyagarajan Ramanujam
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15302
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Thyagarajan Ramanujam
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> What can be done to stop the second field getting focus in case to wrong entry?

InputVerifier
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic