我在将 class1 中的一个字段的文本设置为 class2 中的另一个字段时遇到问题。基本上,我有两节课。在class1中,我有一个方法允许用户搜索文件中的单词(从文件中读取),然后当找到该单词时,我想将其设置为class2“field1”。
例如,如果我搜索“San”,则 class2 中的搜索词应显示“San”,第二个词应显示“Aya”。
我不知道我哪里出错了,程序没有显示任何错误。任何帮助将不胜感激。提前致谢。
文件.txt
San Aya
public class MyFileReader {
JTextField searchfield = new JTextField(10);
JPanel panel = new JPanel();
public MyFileReader() {
panel.add(new JLabel("Search:"));
panel.add(searchfield);
panel.setLayout(new GridLayout(5, 2));
int result = JOptionPane.showConfirmDialog(null, panel,
"Search", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
MyContentManager contentManager = new MyContentManager();
try {
String stringSearch = searchfield.getText();
BufferedReader bf = new BufferedReader(new FileReader("file.txt"));
int linecount = 0;
String line;
ArrayList<String> list = new ArrayList<String>();
while ((line = bf.readLine()) != null) {
list.add(line);
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1) {
String[] word = line.split("\t");
String firstword = word[0];
String secondword = word[1];
contentManager.field1.setText(stringSearch);//This is the problem
contentManager.field2.setText(secondword);//This is the problem
}
}
bf.close();
} catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
public static void main(String[] args) {
new MyFileReader();
}
}
类2
public class MyContentManager {
JTextField field1 = new JTextField(10);
JTextField field2 = new JTextField(10);
JPanel panel = new JPanel();
public MyContentManager() {
panel.add(new JLabel("Searched For:"));
panel.add(field1);
panel.add(new JLabel("Second word:"));
panel.add(field2);
panel.setLayout(new GridLayout(5, 2));
int result = JOptionPane.showConfirmDialog(null, panel,
"Search found", JOptionPane.YES_NO_OPTION);
}
}