Handling events between classes
class, communication, events, java, swing
Solution
You can create an interface `ValueSubmittedListener`
interface ValueSubmittedListener {
public void onSubmitted(String value);
}
and have `Editor` implements it.
class Editor implements ValueSubmittedListener{
...
public void onSubmitted(String value) {
// add text to JTextPane.
}
}
Then have `Toolbar` provide methods
class Toolbar {
private List<ValueSubmittedListener> listeners = new ArrayList<ValueSubmittedListener>();
public void addListener(ValueSubmittedListener listener) {
listeners.add(listener);
}
private void notifyListeners() {
for (ValueSubmittedListener listener : listeners) {
listener.onSubmitted(textfield.getText());
}
}
}
Then everytime you need to send new value to Editor (i.e: in `submitButton`'s `ActionListener`), just invoke the method `notifyListeners`.
UPDATE:
I forgot to mention that in the `initComponents` of `Main`, you have to register `Editor` to `Toolbar`:
private void initComponents() {
JFrame mainframe = new JFrame("Main Frame");
Editor editor = new Editor();
Toolbar toolbar = new Toolbar();
toolbar.addListener(editor); // register listener
...
}
Problem
I have a main class with an Editor class (with a JTextPane) and a Toolbar class (with a JList and a Jbutton, I don't want to use JToolBar). These two classes are composed by many components and I would like not to mix them into the same class. I want the editor and the toolbar to communicate. Let's say I write "Hello" in the toolbar and then click on Submit. I want the text pane to show me "Hello". I build the classes this way: ``` public class Main{ public MainGUI(){ initComponents(); } private void initComponents(){ JFrame mainframe=new JFrame("Main Frame"); Editor editor=new Editor(); Toolbar toolbar=new Toolbar(); mainframe.getContentPane().setLayout(new BorderLayout()); mainframe.getContentPane().add(editor, BorderLayout.CENTER); mainframe.getContentPane().add(toolbar, BorderLayout.NORTH); mainframe.setVisible(true); } } public class Editor extends JPanel{ public Editor(){ super(); initComponents(); } private void initComponents(){ JTextPane textpane=new JTextPane(); this.setLayout(new BorderLayout()); this.add(textpane, BorderLayout.CENTER); } } public class Toolbar extends JPanel{ public Toolbar(){ super(); initComponents(); } private void initComponents(){ JTextField textfield=new JTextField(); JButton submitbutton=new JButton("Submit"); this.setLayout(newFlowLayout()); this.add(textfield); this.add(submitbutton); } } ``` How should I implement the event handling betweenthe Toolbar and the Editor?