Reputation: 25
I use the following code for creating generic class.this code is mainly used for Got focus in text Field in java.suppose we give tab or Shift tab key the JTextField texts will selected.how can i implement this generic class to main function I don't know how to implement generic class in java program
import java.awt.FlowLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
//import javax.swing.text.JTextComponent;
class MyFocusListener<T extends JTextField> extends FocusAdapter {
public void focusGained(FocusEvent evt) {
final T c = (T)evt.getSource();
String s = c.getText();
c.requestFocus();
c.selectAll();
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) {
c.setSelectionStart(i);
c.setSelectionEnd(i);
break;
}
}
}
public void focusLost(FocusEvent evt) {
final T c = (T) evt.getSource();
String s = c.getText();
if (evt.isTemporary()) {
return;
}
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) {
c.requestFocus();
c.selectAll();
break;
}
}
}
}
Upvotes: 0
Views: 246
Reputation: 274748
You need to add that FocusListener
to a JTextField
like this:
You use it like this:
JTextField tf = new JTextField();
tf.addFocusListener(new MyFocusListener<JTextField>());
Upvotes: 1