javaswingawtjbuttonjtoolbar

Add a different ActionListener to anonymously referenced JButtons in a JToolBar


I'm trying to add four JButtons to a JToolBar, each with a different ActionListener.

I'm wondering if there is a way to add an ActionListener to an anonymously referenced JButton, or if I have to specifically define each button and add each listener.

Currently, this is what the code looks like:

JToolBar tools = new JToolBar();
tools.setFloatable(false);
gui.add(tools, BorderLayout.PAGE_START);// adds tools to JPanel gui made in another method

// add buttons to toolbar
tools.add(new JButton("New"));
tools.add(new JButton("Save"));
tools.add(new JButton("Restore"));
tools.addSeparator();
tools.add(new JButton("Quit"));

I was wondering if there was a way to add an ActionListener into the tools.add(new JButton("foo")); line in the same manner as Thread t = new FooRunnableClass().start(); or if I would have to define each button, add the ActionListener to each button, then add each button to tools.


Solution

  • You could define a addButtonToToolbar method to help you out (assuming you are using Java 8 or newer):

    JToolBar tools = new JToolBar();
    tools.setFloatable(false);
    // adds tools to JPanel gui made in another method
    gui.add(tools, BorderLayout.PAGE_START);
    
    addButtonToToolbar(tools, "New", e -> System.out.println("Pressed New"));
    addButtonToToolbar(tools, "Save", e -> System.out.println("Pressed Save"));
    addButtonToToolbar(tools, "Restore", e -> System.out.println("Pressed Restore"));
    tools.addSeparator();
    addButtonToToolbar(tools, "Quit", e -> System.out.println("Pressed Quit"));
    
    
    private void addButtonToToolbar(final JToolBar toolBar, final String buttonText,
                                    final ActionListener actionListener) {
        final JButton button = new JButton(buttonText);
        button.addActionListener(actionListener);
        toolBar.add(button);
    }