Java ActionEvent get event source
import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; public class Main extends JFrame { public Main() { super("JButton"); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new FlowLayout()); /*from w w w . j a v a 2 s . c om*/ JButton bn = new JButton("Close"); bn.addActionListener(e->{ System.out.println(e.getSource() == bn); }); getContentPane().add(bn); } public static void main(String[] args) { Main frame = new Main(); frame.pack(); frame.setVisible(true); } }
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class Main { public static void main(String[] args) { JPanel panel = new JPanel(); JButton close = new JButton("Close"); close.addActionListener(new ButtonListener()); JButton open = new JButton("Open"); open.addActionListener(new ButtonListener()); JButton find = new JButton("Find"); find.addActionListener(new ButtonListener()); JButton save = new JButton("Save"); save.addActionListener(new ButtonListener()); panel.add(close);/* w ww. ja va 2s.c om*/ panel.add(open); panel.add(find); panel.add(save); JFrame f = new JFrame(); f.add(panel); f.setSize(400, 300); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } } class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { JButton o = (JButton) e.getSource(); String label = o.getText(); System.out.println(label + " button clicked"); } }