0

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);
            }
        }
    }
1
Contributor
1
Reply
2
Views
7 Years
Discussion Span
Last Post by LianaN
0

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...

Edited by LianaN: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.