user3079597
user3079597

Reputation:

JTextField is not reading the data input by the user

Here I am trying to make a Swing Java app, where I am getting a String from the JTextField t1 and comparing it whether it matches with any other string in a text file and then displaying the matched String in the JTextField t2. However, the JTextField t1 doesn't even reads the input by the user(I have tried even displaying the input by the user) *Note:-*There is no problem with the 'main' or with the GUI of this program.

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");}
}

Upvotes: 0

Views: 303

Answers (3)

ruben056
ruben056

Reputation: 112

In your actionperformed method you are creating a second String a variable in another scope : the scope of that function. So you are not initializing the value to static String a but to String a (function scope). In the atomicNumber() function you are referencing the static String a variable which is not initialized... Try following solution, change:

String a = t1.getText();

To

a = t1.getText();

Upvotes: 0

Kick
Kick

Reputation: 4923

Create instance variable a and set this variable in the method actionPerformed and use this instance variable in another method atomicnumber .

You need to make the method atomicnumber as non-static to access it.

Upvotes: 3

StreamingBits
StreamingBits

Reputation: 137

You make an instance variable. You need to make it 'visible'. Also where is your startsWith method? Make sure you are passing the correct parameters.

pseudo code

class SomeClass {
    var1 < THIS IS an instance method accessible to any method in that class

method1 {
    var2

}

method2 {
   something.doSomeMethodOn(var2) <<<<< THIS is NOT accessible
   something.doSomeMethodON(var1)<<< THIS IS!
}

Upvotes: 0

Related Questions