I have a problem setting the text of a field in class1 to another field in class2. Basically, I have two classes. In class1 i have a method that allows the user to search for a word that is in a file(reading from file) and then when the word is found, i want to set it to the class2 "field1".
For example, if i search for "San", the searched word in class2 should show "San" and the second word should show "Aya".
I dont know where iam going wrong and the program doesn't show any errors. Any help will be appreciated. Thanks in advance.
file.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();
}
}
class2
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);
}
}
class2 was built before the search, you have to delay it's instantiation and add two arguments in its constructor to set the fields with the proper values.
JOptionPane was shown in the constructor, if you want to use settter as commented, you have to move the dialog to this setter.
I would give your 2nd class setter methods, have it produce a JPanel that can be obtained via a getter method, and simply display it in a JOptionPane (if desired). For instance:
DamClass1.java
DamClass2.java
Please put in some effort to post better formatted code when asking a question here.
You need to change the second class to some like:
This will deal with showing the fields when you find them. Now your first class needs to do something like:
Not sure what you want to do with the result from showing the words but I have changed the second class to return the value.