2012-05-02 15 views
-3

私は元の投稿を編集していませんので、誰もタイトルをもう一度主張することはできません(それは私のせいですので、今度は気違いません)... 私はTextFieldのテキスト(実際には2つのTextFieldがありますが、ユーザは一度に1つしか使用できません)を取得し、それを端末に格納されたファイルに検索します。JTextFieldからテキストを取得する際の文字列ヌル

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

}

私は本当にすべてをスローするつもりです:問題は、TextFieldの1 ... これにテキストがある場合でも、私はいつも、ヌル文字列を取得するコードです窓の外に原因常にline.contains(str)ためtrueを与えることが保証されstr

+1

ごめんなさい... "HELLO"を頭に入れないのを忘れたxD –

+7

'str'の値は? – NPE

+0

あなたの質問を閉じてください。 –

答えて

6

のみ値が空Stringです...私は解決策は単純です知っているが、私はそれを取得することはできません。


(あなたはString.contains方法は、その仕様に従って作業を行うことを想定する必要があります。Java SEのに非常に中央の方法で未検出のバグの可能性は、あなたがいる限り壮観です特にバグごくわずかです確かに、何の証拠もなく壊れていると主張しているのは、誰もが時間を無駄にしようとしているだけです...そして、特にあなたのものです)

+0

Downvoterは説明しやすいですか? –

+1

*「確かな証拠がなくても壊れていると主張しているのは、誰もが時間を無駄にしているだけだ...そして、特にあなたのもの」* –

+0

だから、いくつかの点を明確にしよう: - まず何も主張していない。 "String.contains does not work"は、メソッドが盗まれているなどの意味ではありません。これは、この場合、この質問またはその質問に対しては機能しません。告発する前に考えてみてください... –

関連する問題