java JTextField未读取用户输入的数据
在这里,我尝试制作一个Swing Java应用程序,从JTextField t1
中获取一个String
,比较它是否与文本文件中的任何其他字符串匹配,然后在JTextField t2
中显示匹配的String
。但是,jtextfieldt1甚至不读取用户的输入(我甚至尝试显示用户的输入)
*注意:-*此程序的“main”或GUI没有问题
JButton b1;
JTextField t1,t2;
public void actionPerformed(ActionEvent ae){try{
String a=t1.getText();
String search="";
try{
if(a.length()!=0){
search=atomicnumber(a);
t2.setText(a);}
}catch(Exception x){System.out.println("Error");}
}catch (Exception x) {System.err.println("An Unexpected error encountered."+x);}
}
public static String atomicnumber(String a){try{
boolean found=false;
File atmno=new File("C:/Users/DELL/Periodic/text/AtomicNumber.txt");
String e;
Scanner sc=new Scanner(atmno);
while((e = sc.nextLine()) != null){
if (e.startsWith(a)){
found=true;
return e;//break;
}
return("0");}}catch(IOException x){}
return("0");}
}
# 1 楼答案
在actionperformed方法中,您正在另一个作用域(该函数的作用域)中创建第二个字符串变量。因此,您没有将值初始化为静态字符串a,而是初始化为字符串a(函数范围)。在atomicNumber()函数中,您引用的是未初始化的静态字符串变量。。。 尝试以下解决方案,更改:
字符串a=t1。getText()
到
a=t1。getText()
# 2 楼答案
创建实例变量a并在方法
actionPerformed
中设置此变量,并在另一个方法atomicnumber
中使用此实例变量您需要将方法
atomicnumber
设置为非静态才能访问它# 3 楼答案
创建一个实例变量。你需要让它“可见”。你的startsWith方法在哪里?确保传递的参数正确
伪码