【发布时间】:2017-03-02 17:06:38
【问题描述】:
无法解决这个问题。 我想用 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" 但它会是 ""
【问题讨论】:
-
所有这些代码都在做什么?对不起,但它看起来很乱。建议: 1)去掉key listener。您永远不应该将 keyListeners 添加到 Swing 文本组件,因为这会扰乱文本组件的固有功能(正如您所发现的那样)。而是使用 DocumentListeners 或 DocumentFilters,因为许多类似的问题答案会告诉您。 3)为什么每次激活侦听器时都要读取和重新读取文件?这看起来像您让程序执行不必要且昂贵的重复操作。不要这样做。读入文件一次。
-
基本上我要做的是读取用户的输入,这个输入(这是一个数字)将在一个包含数字和日期列表的 .txt 文件中进行搜索。示例:.txt 文件的第一行是“1:1-01-2017”第二行是 2:8-01-2017”第三行是“3:15-01-2017 等等。所以我想要什么要做的是在这个 .txt 文件中搜索“:”之前的那个数字,当它找到它时,在另一个文本字段中写入日期。例子。用户在 textfield1 中写入“3”,程序将在 .txt 文件中搜索“:”之前的数字 3,找到后,将日期写入另一个文本字段。
标签: java swing keylistener