无法解决这个问题。 我想检索使用 keyTyped 在文本字段中写入的文本并将 int 放在字符串上。但如果我这样做,它会给我一个空白字符串。我能做什么?
textField_9.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e){
xw = textField_9.getText(); //should retrieve my input
}
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if((!(Character.isDigit(c)) && (c!='.'))){
e.consume();
}
System.out.println(xw); //gives nothing ("") not null
numero = e.getKeyChar();
String fileName = defaultx+"\\"+"Contratti"+"\\"+textField_7.getText()+"\\"+"lista"+tipo;
Scanner scanner;
try {
scanner = new Scanner(new File(fileName));
scanner.useDelimiter(":");
while(scanner.hasNext()){
num = scanner.next();
System.out.println("Numero = "+num+"\t"+xw); //debug
dat = scanner.nextLine().replaceAll(":", "");
if(num == xw){
try(Scanner scanner1 = new Scanner(dat)){
scanner1.useDelimiter(":");
giorno = scanner1.next();
meset = scanner1.next();
anno = scanner1.next();
System.out.println(giorno+"-"+meset+"-"+anno); //debug
}catch(NoSuchElementException ex){
}
}else{
System.out.println("Dato non trovato");
}
}
scanner.close();
} catch (FileNotFoundException e1) {
} catch(NoSuchElementException e1){
}
}
});
示例
我在 JTextField 中写入数字“5”,xw 应该是“5”,但它会是“”
最佳答案
Basically what I'm trying to do is to read user's input, this input (that's a number) will be searched in a .txt file that contains a list of number and dates. example : 1st line of the .txt file is "1:1-01-2017" the second line is 2:8-01-2017" the third line is "3:15:01:2017 etc..
一次读取此数据,而不是像您在上面尝试执行的那样每次按键一次,也许在类的构造函数中执行此操作。然后将数据存储在可搜索的集合中,可能是自定义类的数组列表。
so what I want to do is to search in this .txt file that number before ":" and when it finds it ,write in another textfield the date. example. user write in textfield1 "3", the program will search in the .txt file the number 3 that is before the ":" and when it find it , will write the date into another textfield.
保存文本文件数据的自定义类应该在自己的字段中保存单独的数字,并在需要时再次搜索这些对象的 ArrayList。
另外:
- 不要将 KeyListener 添加到 JTextField,因为这会阻止 JTextField 正常运行(正如您所发现的那样)。
- 我们有时会向 JTextField 的文档添加 DocumentListener 或 DocumentFilter 以实现类似的行为...
- 但就你而言,我也不会这样做。相反,将 ActionListener 添加到 JTextField(按下 ENTER 键时激活的监听器),并从此监听器中搜索 ArrayList。
- 您应该几乎永远没有空的catch block ,正如我们在上面的代码中看到的那样。至少打印出堆栈跟踪,因为您很可能会遇到在您不知情的情况下完全抛出异常的问题,因为您的代码会忽略它们。
关于java - keyTyped 使 JTextField 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42561619/