JTextField.getText()返回null值,即使其中包含内容

时间:2012-05-02 15:26:41

标签: java swing null jtextfield file-read

我有一部分代码采用TextField的文本(实际上有两个TextField,但用户一次只能使用一个)并将其搜索到存储在终端中的文件中。问题是我总是得到一个空字符串,即使其中一个TextFields有文本... 这是代码(赋值在方法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();
}

}

我真的要扔掉窗外的所有东西,因为我知道解决方案很简单,但我无法得到它......

2 个答案:

答案 0 :(得分:2)

正如以下测试所证实,自null调用起,您的 字段不是actionListener 。例如,按预期输入"Comando""Carico"输出"Test: Comando"后跟"Test: Carico"

@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());
    }
  }
}

问题是if (textv != null)在第一次运行时永远不会到达“其他”(据我所知,我给出了代码的快速查看,它永远不会出现在 任何 运行,因为textv永远不会设置null),因为textv = new JTextField("");不等同于textv = nulltextv将仍然持有一个字符串,虽然它是空的。

解决方法是:

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

您还错过了C:\Log.txt存在的验证,并且可以轻松触发异常。

以下是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();
}

答案 1 :(得分:0)

使用JTextArea#read(Reader in, Object desc) throws IOException,此方法接受行分隔符e.i.