I have two different FileMenuHandler’s for a GUI, I need a way to use the data stored in the TreeMap from FileMenuHadler in EditMenuHandler. EditMenuHandler is supposed to ask the user to enter a word and search in the TreeMap if the word exists.
I tried to create an instance of FMH in EMH but the Tree was always empty, how can I save the values of the tree once the file is opened and then use it for EditMenuHandler?
import java.util.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class FileMenuHandler implements ActionListener{ JFrame jframe;//creating a local JFrame public FileMenuHandler (JFrame jf){//passing WordGUI Jframe jframe = jf; } private Container myContentPane; private TextArea myTextArea1; private TextArea myTextArea2; protected ArrayList<Word> uwl = new ArrayList<Word>(); protected TreeMap<Word, String> tree; private void readSource(File choosenFile){ String choosenFileName = choosenFile.getName(); TextFileInput inFile = new TextFileInput(choosenFileName); myContentPane = jframe.getContentPane(); myTextArea1 = new TextArea(); myTextArea2 = new TextArea(); myTextArea1.setForeground(Color.blue); myTextArea2.setForeground(Color.blue); Font font = new Font("Times", Font.BOLD, 20); myTextArea1.setFont(font); myTextArea2.setFont(font); myTextArea1.setBackground(Color.yellow); myTextArea2.setBackground(Color.yellow); String paragraph = ""; String line = inFile.readLine(); while(line != null){ paragraph += line + " "; line = inFile.readLine(); } StringTokenizer st = new StringTokenizer(paragraph); tree = new TreeMap<Word,String>(); while(st.hasMoreTokens()){ String word = st.nextToken(); Word w = new Word(word); uwl.add(w); tree.put(w,w.data); } for(int i = 0; i < uwl.size(); i++){ myTextArea1.append(uwl.get(i).data + "n"); } myTextArea2.append(tree + "n"); myContentPane.add(myTextArea1); myContentPane.add(myTextArea2); jframe.setVisible(true); } private void openFile(){ int status; JFileChooser chooser = new JFileChooser("./"); status = chooser.showOpenDialog(null); readSource(chooser.getSelectedFile()); } //instance of edit menu handler public void actionPerformed(ActionEvent event) { String menuName = event.getActionCommand(); if (menuName.equals("Open")){ openFile(); } else if (menuName.equals("Quit")){ System.exit(0); } } //actionPerformed } //
import java.awt.event.*; public class EditMenuHandler implements ActionListener { JFrame jframe; public EditMenuHandler(JFrame jf) { jframe = jf; } public void actionPerformed(ActionEvent event) { String menuName = event.getActionCommand(); if (menuName.equals("Search")) { JOptionPane.showMessageDialog(null, "Search"); } } }
Advertisement
Answer
there are many ways to do this,
- you can declare a static filed (not recommended)
- use RXJava or LiveData
- use EventBus
- use interface as a listener ….