单击了哪个按钮。 Java中,Netbeans的

时间:2013-10-29 21:22:46

标签: java swing button netbeans

我使用Netbeans在java中创建一个应用程序。在Jframe表格中,我使用了四个按钮。我需要知道用户点击了哪些。谁能帮帮我? 感谢

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);
            }
        });
    }

3 个答案:

答案 0 :(得分:2)

您可以在getSource上致电ActionEvent以查找活动来源。这将是其中一个按钮。

答案 1 :(得分:2)

  

我需要知道哪些用户点击了

只需实施actionPerformed方法并在getSource()变量上调用ActionEvent即可知道点击了哪个按钮:

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

您也可以直接将听众添加到按钮中:

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

答案 2 :(得分:0)

处理程序的ActionEvent参数将包含对创建事件的对象(按钮)的引用。

(继承自EventObject)

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