Hi!

I would like to add ActionListener to buttons stored in JToolBar. However, if I'm using the code bellow, then I could add only MouseListener ("addActionListener" doesn't work). So, is it possible to somehow add ActionListener? Thanks a lot!

JToolBar toolBarUpdateDocs = new BrowserToolBar();
        toolBarUpdateDocs.setFloatable(false);   
toolBarUpdateDocs.getComponent(i).addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        System.out.println("Ok");
                    }
                  });
...

 private class BrowserToolBar extends JToolBar {
        private BrowserToolBar() {
                String[] imageFiles =
                  { "add.png", "del.png", "search.png" };
                String[] toolbarLabels =
                  { "Add", "Delete", "Find" };
                Insets margins = new Insets(0, 0, 0, 0);
                for(int i=0; i<toolbarLabels.length; i++) {
                  ToolBarButton but = new ToolBarButton("src/icons/" + imageFiles[i]);
                  but.setToolTipText(toolbarLabels[i]);
                  but.setMargin(margins);
                  add(but);
            }
        }
    }

Ok, I've solved this problem in the following way:

private class BrowserToolBar extends JToolBar {
        private BrowserToolBar(String[] imageFiles, String[] toolbarLabels) {
                Insets margins = new Insets(0, 0, 0, 0);
                for(int i=0; i<toolbarLabels.length; i++) {
                  ImageIcon ic = new ImageIcon("src/icons/" + imageFiles[i]);
                  JButton but = new JButton(ic);
                  but.setToolTipText(toolbarLabels[i]);
                  but.setMargin(margins);
                  add(but);
            }
        }

        private JButton getButton(int i) {
            return (JButton) this.getComponent(i);
        }
    }

...

toolBarUpdateUsers.getButton(0).addActionListener...
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.