简体   繁体   中英

Which button has clicked. Java,Netbeans

I make an app in java with Netbeans. At a Jframe Form,I use four buttons. I need to know which of them has clicked by user. Everyone who can help me? Thanks

public class Color extends javax.swing.JFrame implements ActionListener {


public Color() {
        initComponents();


        /////////////////////////////////

        //Register a listener for the  buttons.
        up_button.addActionListener(this);
        down_button.addActionListener(this);
        left_button.addActionListener(this);
        right_button.addActionListener(this);
       }


private int k=1;
    public void actionPerformed(ActionEvent e) {

       k=k+1;


       if (k==1)
       {
         image.setIcon(createImageIcon("color1"
                                        + e.getActionCommand()
                                        + ".PNG"));
       }
       else ...  }

       private void up_buttonActionPerformed(java.awt.event.ActionEvent evt)     {                                          
        // TODO add your handling code here:

    }  

    private void down_buttonActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:

    }

    public static void main(String args[]) {

        /* Create and display the form */

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Color().setVisible(true);
            }
        });
    }

You can call getSource on the ActionEvent to find out the source of the event. That will be one of the buttons.

I need to know which of them has clicked by user

Just implement the actionPerformed method and call getSource() on the ActionEvent variable to know which button has been clicked :

public void actionPerformed(ActionEvent e){
      if(e.getSource() == up_button){
         //up_button clicked
      }       
}

You could also add directly the listener to your button :

up_button.addActionListener(new ActionListener(){ 
     public void actionPerformed(ActionEvent e){
        //Button is pressed
     }
 });   

The ActionEvent parameter to the handler will contain a reference to the object (button) that created the event.

(inherited from EventObject)

http://docs.oracle.com/javase/7/docs/api/java/util/EventObject.html#getSource()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM