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?
You can create an interface
ValueSubmittedListenerand have
Editorimplements it.Then have
Toolbarprovide methodsThen everytime you need to send new value to Editor (i.e: in
submitButton‘sActionListener), just invoke the methodnotifyListeners.UPDATE:
I forgot to mention that in the
initComponentsofMain, you have to registerEditortoToolbar: