Swing: Linking Toggle Buttons with a Button Group and Menu Items
In the context of a simple paint application with toolbar buttons and menu items for different shapes, the question arises: how to ensure that selecting a toolbar button deselects the others and selects the corresponding menu item, and vice versa.
While the ButtonGroup class can handle selection within a single group of buttons, it may not be the most suitable solution for handling multiple groups. Furthermore, it introduces the risk of infinite recursion if the menu modifies the button, and vice versa.
A better approach lies in the use of Actions. The Action interface allows multiple components, such as buttons and menu items, to perform the same function. By using the same Action for each group, you can ensure consistent behavior without the need for manual handling of button selection and shape setting.
To illustrate this, the following code snippet demonstrates how to share Actions between a JMenu and a JToolBar for managing recent files:
import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.io.File; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JToolBar; public class FileMenu { public void create() { File userDir = new File(System.getProperty("user.dir")); File[] files = userDir.listFiles(); JMenu menu = new JMenu("Recent Files"); JToolBar toolBar = new JToolBar(JToolBar.VERTICAL); JLabel label = new JLabel(" ", JLabel.CENTER); for (File f : files) { if (f.isFile() && !f.isHidden()) { RecentFile rf = new RecentFile(f, label); menu.add(new JMenuItem(rf.getAction())); toolBar.add(rf.getAction()); } } JMenuBar menuBar = new JMenuBar(); menuBar.add(menu); JFrame f = new JFrame("FileMenu"); f.setJMenuBar(menuBar); f.add(toolBar, BorderLayout.CENTER); f.add(label, BorderLayout.SOUTH); f.pack(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setLocationRelativeTo(null); f.setVisible(true); } class RecentFile extends AbstractAction { private final File file; private final JLabel label; public RecentFile(final File file, final JLabel label) { this.file = file; this.label = label; this.putValue(Action.NAME, file.getName()); this.putValue(Action.SHORT_DESCRIPTION, file.getAbsolutePath()); } public void actionPerformed(ActionEvent e) { label.setText(file.getName()); } public Action getAction() { return this; } } }
By using the same Action for both the toolbar buttons and the menu items, you achieve the desired behavior where selecting a button deselects the others and selects the corresponding menu item, and vice versa without any manual handling or risk of infinite recursion.
The above is the detailed content of How to Synchronize Toggle Button Selection Between JToolBar and JMenu in Swing?. For more information, please follow other related articles on the PHP Chinese website!