将单个动作侦听器附加到所有按钮

我有一个包含许多按钮的程序,所有按钮都将执行相同的function。 我想知道是否有办法将单个侦听器附加到程序中的所有现有JButton。

就像是:

import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class CalculatorPanel extends JPanel { private JTextField display; public CalculatorPanel() { Action numberAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { display.setCaretPosition( display.getDocument().getLength() ); display.replaceSelection(e.getActionCommand()); } }; setLayout( new BorderLayout() ); display = new JTextField(); display.setEditable( false ); display.setHorizontalAlignment(JTextField.RIGHT); add(display, BorderLayout.NORTH); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout( new GridLayout(0, 5) ); add(buttonPanel, BorderLayout.CENTER); for (int i = 0; i < 10; i++) { String text = String.valueOf(i); JButton button = new JButton( text ); button.addActionListener( numberAction ); button.setBorder( new LineBorder(Color.BLACK) ); button.setPreferredSize( new Dimension(50, 50) ); buttonPanel.add( button ); KeyStroke pressed = KeyStroke.getKeyStroke(text); InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(pressed, text); button.getActionMap().put(text, numberAction); } } private static void createAndShowUI() { // UIManager.put("Button.margin", new Insets(10, 10, 10, 10) ); JFrame frame = new JFrame("Calculator Panel"); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.add( new CalculatorPanel() ); frame.pack(); frame.setLocationRelativeTo( null ); frame.setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { createAndShowUI(); } }); } } 

Action将从Event获取源对象,以便它知道单击了哪个按钮。

如果您需要在Action中使用if / else逻辑,那么您应该创建一个单独的Action。 如果代码不属于某个Action,请不要强制执行。

只需将ActionListener添加到按钮即可。

对于取决于源的特定操作,您可以使用我编写的内容或使用ActionCommands (它基本上将某些组件链接到在事件上发送到ActionListener的’命令’)。

这是一个小例子:

 public class MyClass implements ActionListener { JButton button1; JButton button2; JButton button3; public MyClass() { button1 = new JButton(); button2 = new JButton(); button3 = new JButton(); button1.addActionListener(this); button2.addActionListener(this); button3.addActionListener(this); } @Override public void ActionPerformed(ActionEvent e) { //do stuff //if you want to do something depending on the button pressed //check the source if (e.getSource() == button1) { //do stuff } } } 

你可以…

创建ActionListner的单个实例并将其应用于所有按钮

你可以…

使用Actions API,它将允许您创建一个自包含的ActionListerner,其中还包括配置按钮的详细信息。

有很多方法可以做到这一点。

你控制这些按钮的创建吗? 如果是,请在返回对象之前创建工厂并附加侦听器

否则,您可以遍历swing tree并检查JButton的实例并附加到匹配项上

您还可以考虑ActionMap / InputMap方法,其中可以根据焦点策略存储和调用操作。

另外,你可以扩展JButton ….