0

I'm constructiong a simple GUI program. One of the classes is a Toolbar (JPanel) with several buttons. The other class is the main Window, which includes this Toolbar and its buttons. I'm trying to add action listeners to each of the buttons, so they execute methods of the Window on other components, like other JPanels.

To my knowledge, the obvious solution would be to add Listeners to the Window class, like so:

class Window
{
    private Toolbar toolbar;

    private void *methodOnOtherWindowComponents*() {
        ....;
    }

    // Method to add Listeners on Buttons via anonymous classes
    private void addListeners() {
        toolbar.getButton().addActionListener(
             new ActionListener() {
                 public void actionPerformed(ActionEvent event){
                    *methodOnOtherWindowComponents()*

However, since the Window class only serves the purpose of putting things together, adding Listeners seems to make it too complicated.

If I try to add Listeners in the Toolbar class, where the buttons are created (better solution) or in a separate class (most desirable solution), then I can't reference the methodToExecute() in the Window class.

I'm hopefully looking for a way to add a listener like so:

void actionPerformed(ActionEvent event, Window w) {
    w.methodOnOtherWindowComponents()
}

Is there a way to something similar? Thank you.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 1
    The canonical solution to this is to give your overall program a Model-View-Controller or MVC structure where your menus call controller methods that change the state of the model. This is then reflected in changes in the view. Please look this up. – Hovercraft Full Of Eels Apr 16 '17 at 19:18
  • [For example](http://stackoverflow.com/a/26518274/522444) as well as [this example](http://stackoverflow.com/a/20027965/522444) and also [this example](http://stackoverflow.com/a/15729267/522444) – Hovercraft Full Of Eels Apr 16 '17 at 19:20

0 Answers0