Java动作监听器

我的程序中有4个按钮列表。 截至目前,我有4个循环,检查是否已点击按钮。 有没有一种简单的方法来检查是否已经点击任何按钮而不是循环遍历每个列表以查看是否单击了某个按钮。 必须有一种更简单的方法来检查“actionSource == anybutton”…

为每个按钮使用匿名内部类:

JButton button = new JButton("Do Something"); button.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Do Something Clicked"); } }); 

或者,如果您的逻辑是相关的,那么您可以共享一个监听器:

 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ButtonCalculator extends JFrame implements ActionListener { private JButton[] buttons; private JTextField display; public ButtonCalculator() { display = new JTextField(); display.setEditable( false ); display.setHorizontalAlignment(JTextField.RIGHT); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout( new GridLayout(0, 5) ); buttons = new JButton[10]; for (int i = 0; i < buttons.length; i++) { String text = String.valueOf(i); JButton button = new JButton( text ); button.addActionListener( this ); button.setMnemonic( text.charAt(0) ); buttons[i] = button; buttonPanel.add( button ); } getContentPane().add(display, BorderLayout.NORTH); getContentPane().add(buttonPanel, BorderLayout.SOUTH); setResizable( false ); } public void actionPerformed(ActionEvent e) { JButton source = (JButton)e.getSource(); display.replaceSelection( source.getActionCommand() ); } public static void main(String[] args) { UIManager.put("Button.margin", new Insets(10, 10, 10, 10) ); ButtonCalculator frame = new ButtonCalculator(); frame.setDefaultCloseOperation( EXIT_ON_CLOSE ); frame.pack(); frame.setLocationRelativeTo( null ); frame.setVisible(true); } } 

您可以为每个按钮添加单个侦听器,并为每个按钮添加一个公共侦听器。 对公共监听器进行编程以响应“按下任何按钮”。

无论actionPerformed单击按钮,它都会触发actionPerformed方法,无论您按下哪个按钮。

 public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if (source instanceof JButton) System.out.println("You clicked a button!"); }