import java.awt.event.*; import javax.swing.*; public class MouseClickExample extends JPanel implements MouseListener{ public MouseClickExample(){ addMouseListener(this); } public void mouseClicked(MouseEvent e){ Component comp = e.getComponent(); JOptionPane.showMessageDialog(comp, "You clicked on " + comp.getName()); } }
import java.awt.event.*; import javax.swing.*; public class ButtonClickExample extends JFrame implements ActionListener{ private JButton button1, button2; public ButtonClickExample(){ button1 = new JButton("Button 1"); button2 = new JButton("Button 2"); button1.addActionListener(this); button2.addActionListener(this); add(button1); add(button2); } public void actionPerformed(ActionEvent e){ Component comp = e.getComponent(); JOptionPane.showMessageDialog(comp, "You clicked on " + comp.getName()); } }Both these examples use the getComponent() method of the MouseEvent class to determine which component was clicked and display a message accordingly.