'How to duplicate actions to a JToolBar?
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?
Solution 1:[1]
- You don't need your ToolBar class. The JToolBar does everything you need.
- Create all of your Actions and place them into an ActionMap.
- 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ryan |
