Search code examples
javaswingnulljtextfieldfile-read

JTextField.getText() returns null value even if it has content inside


I have a portion of code that takes the text of a TextField (there are two TextFields actually, but the user can use only one at a time) and search it into a file stored into the terminal. The problem is that I always get a null string, even when there is text into one of the TextFields... This is the code (the assignation is on the method actionPerformed():

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class Search implements ActionListener{
JFrame frame;
JButton click;
JLabel comando, carico;
JTextField textv, text;
JTextArea res;
String pathFile = "C:\\Log.txt";
String str= new String();

Search(){

    frame = new JFrame("Search");
    frame.setSize(400, 200);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new GridLayout(1,2));
    frame.setResizable(false);
    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(7,1));
    click = new JButton("Cerca");
    comando = new JLabel("Comando");
    carico = new JLabel("A carico di:");
    textv = new JTextField("");
    text = new JTextField("");
    res = new JTextArea("");
    panel.add(comando);
    panel.add(textv);
    panel.add(carico);
    panel.add(text);
    panel.add(click);
    res.setLineWrap(true);
    res.setWrapStyleWord(true);
    res.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));

    JScrollPane scroller = new JScrollPane(res);
    scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    panel.add(scroller);
    frame.add(panel);
    click.addActionListener(this);      
    click.setSize(70, 35);      
    frame.setVisible(true);

}

public void actionPerformed (ActionEvent e){
    if(e.getSource()==click){
        res.setText(null);
        if(textv != null) {cercaStringa(pathFile, textv.getText().toString());}
        else {cercaStringa(pathFile, text.getText().toString());}
    }
}

public void cercaStringa(String pathFile, String stringa){
    try {
        BufferedReader in = new BufferedReader(new FileReader(pathFile));
        String line = new String();
        while((line = in.readLine())!=null) {   
            if(line.contains(stringa)){
                res.append(line);
                res.append("\n");
                }
        }
    }
    catch(IOException ex) { ex.printStackTrace();}
    }



public static void main (String[] args){
    new Search();
}

}

I'm really going to throw everything outside the window cause I know the solution is simple but I can't get it...


Solution

  • As confirmed by the following test, your fields are not null as of the actionListener call. For example, input of "Comando" and "Carico" outputs "Test: Comando" followed by "Test: Carico", as expected:

    @Override
    public void actionPerformed(ActionEvent e) {
      if (e.getSource() == click) {
        res.setText(null);
        System.out.println("Test: "+textv.getText());
        System.out.println("Test: "+text.getText());
        if (textv != null) {
          cercaStringa(pathFile, textv.getText().toString());
        } else {
          cercaStringa(pathFile, text.getText().toString());
        }
      }
    }
    

    The problem is that if (textv != null) will never reach the "else" at the first run (as far as I can tell in the quick-look I gave the code, it never will on any run, as textv is never set null), because textv = new JTextField(""); is not equivalent to textv = null, and textv will still be holding a String, albeit it's an empty one.

    The fix is this:

    public void actionPerformed(ActionEvent e) {
      if (e.getSource() == click) {
        res.setText("");
        if (!textv.getText().isEmpty()) {
          cercaStringa(pathFile, textv.getText().toString());
        } else {
          cercaStringa(pathFile, text.getText().toString());
        }
      }
    }
    

    You were also missing a verification for the existence of C:\Log.txt, and an exception could be easily triggered.

    Here is the quick-fix, in the Main:

    public static void main(String[] args) {
      File log = new File("C:\\Log.txt");
      if (!log.exists()) {
        try {
          /*
           * mkdirs() is not really needed when using the C root,
           * but I like to do this because the path might be changed.
           */
          if (!log.getParentFile().exists()) {
            log.getParentFile().mkdirs();
          }
          log.createNewFile();
        } catch (IOException ex) {
          Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
      Search search = new Search();
    }