How to duplicate actions to a JToolBar?

47 Views Asked by At

I have a JMenu setup already. I have created a toolbar with icons but I am unsure how to associate actions with the toolbar buttons. This is how I have made the the toolbar

public class ToolBar {

    ArrayList<JButton> buttons;

    JButton saveButton, exportButton, openButton, rotateLeftButton, rotateRightButton, zoomIButton, zoomOButton;

    public ToolBar() {
        buttons = new ArrayList<JButton>();
        buttons.add(new JButton(new ImageIcon("src/icons8-save-30.png")));
        buttons.add(new JButton(new ImageIcon("src/icons8-export-30.png")));
        buttons.add(new JButton(new ImageIcon("src/icons8-save-30.png")));
        buttons.add(new JButton(new ImageIcon("src/icons8-rotate-left-30.png")));
        buttons.add(new JButton(new ImageIcon("src/icons8-rotate-right-30.png")));
        buttons.add(new JButton(new ImageIcon("src/icons8-zoom-in-30.png")));
        buttons.add(new JButton(new ImageIcon("src/icons8-zoom-out-30.png")));
    }
    
    public JToolBar createToolBar() {
        JToolBar tools = new JToolBar();

        for (int i = 0; i < buttons.size(); i++) {
            tools.add(buttons.get(i));
        }

        return tools;
    }


}

How can I add the below file open action to one of the Jbuttons in the toolbar?

public class FileOpenAction extends ImageAction {

         
        FileOpenAction(String name, ImageIcon icon, String desc, Integer mnemonic) {
            super(name, icon, desc, mnemonic);
            putValue(ACCELERATOR_KEY,
                    KeyStroke.getKeyStroke(KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));

        }

       
       
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            int result = fileChooser.showOpenDialog(target);

            if (result == JFileChooser.APPROVE_OPTION) {
                try {
                    String imageFilepath = fileChooser.getSelectedFile().getCanonicalPath();
                    target.getImage().open(imageFilepath);
                } catch (Exception ex) {
                    System.exit(1);
                }
            }

            target.repaint();
            target.getParent().revalidate();
        }

    }

How can I add the open file action to one of the Jbuttons on the toolbar?

1

There are 1 best solutions below

0
On
  1. You don't need your ToolBar class. The JToolBar does everything you need.
  2. Create all of your Actions and place them into an ActionMap.
  3. When you create your toolbar, you can use toolbar.add(actionMap.get(ACTION_KEY) for each button you want on the toolbar. If you also want that action on a button on a panel, you load the same action using the same key.