rt

解决方案 »

  1.   


    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;import javax.swing.WindowConstants;
    import javax.swing.SwingUtilities;public class EventTest extends javax.swing.JFrame {
    private JPanel MainJPanel;
    private JButton btnName;
    private JButton btnAge;
    private JButton btnSex;
    public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    EventTest inst = new EventTest();
    inst.setLocationRelativeTo(null);
    inst.setVisible(true);
    }
    });
    } public EventTest() {
    super();
    initGUI();
    } private void initGUI() {
    try {
    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); MainJPanel = new JPanel();
    getContentPane().add(MainJPanel, BorderLayout.CENTER); btnName = new JButton();
    MainJPanel.add(btnName);
    btnName.setText("Name"); btnSex = new JButton();
    MainJPanel.add(btnSex);
    btnSex.setText("Sex"); btnAge = new JButton();
    MainJPanel.add(btnAge);
    btnAge.setText("Age"); btnAge.addActionListener(new myActionListener(btnAge));
    btnName.addActionListener(new myActionListener(btnName));
    btnSex.addActionListener(new myActionListener(btnSex)); pack();
    setSize(400, 300);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }}class myActionListener implements ActionListener { Component component; public myActionListener() { }

    public myActionListener(Component component) {
    this.component = component;
    } public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, ((JButton) component).getText()
    .toString());
    }}//仅供参考...
      

  2.   

    所有控件添加同一个监听器,然后在该监听中获取e.getSource()事件中,getSource能够获取当前事件的触发源,你要做的只是监听并获取到它而已
      

  3.   

    先获取鼠标位置,然后转化成坐标
    然后调用
    Component.getComponentAt(int x, int y);
    就可以了