我使用下面的代码来创建泛型类。这个代码主要用于在java.suppose中的文本字段中获取焦点我们给tab或Shift tab键选择JTextField文本。我可以将这个泛型类实现为main函数我不知道如何在java程序中实现泛型类
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;
}
}
}
}
答案 0 :(得分:1)
您需要将FocusListener
添加到JTextField
,如下所示:
你这样使用它:
JTextField tf = new JTextField();
tf.addFocusListener(new MyFocusListener<JTextField>());