本文介绍了一个动作监听器,二Jbutton将的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 Jbutton将所谓的左和右。
左按钮移动的矩形对象向左和右按钮,它移动到右侧。
我在那个充当倾听者被点击时任一按钮为类有一个的ActionListener
不过,我希望每个被点击时,会发生不同的动作。我怎样才能区分,在的ActionListener 单击了的?

I have two JButtons called "Left" and "Right".The "Left" button moves a rectangle object to the left and the "Right" button moves it to the right.I have one ActionListener in the class that acts as the listener for when either button is clicked.However I want different actions to happen when each are clicked. How can I distinguish, in the ActionListener, between which was clicked?

推荐答案

设置 actionCommand 到每个按钮。

//设置的动作命令这两个按钮。

// Set the action commands to both the buttons.

 btnOne.setActionCommand("1");
 btnTwo.setActionCommand("2");

public void actionPerformed(ActionEvent e) {
 int action = Integer.parseInt(e.getActionCommand());

 switch(action) {
 case 1:
         //doSomething
         break;
 case 2:
         // doSomething;
         break;
 }
}

更新:

public class JBtnExample {
public static void main(String[] args) {
    JButton btnOne = new JButton();
    JButton btnTwo = new JButton();

    ActionClass actionEvent = new ActionClass();

    btnOne.addActionListener(actionEvent);
            btnTwo.addActionListener(actionEvent);

    btnOne.setActionCommand("1");
    btnTwo.setActionCommand("2");
}
}

class ActionClass implements ActionListener {

@Override
public void actionPerformed(ActionEvent e) {
    int action = Integer.parseInt(e.getActionCommand());
    switch (action) {
    case 1:
        // DOSomething
        break;
    case 2:
        // DOSomething
        break;
    default:
        break;
    }
}
}

这篇关于一个动作监听器,二Jbutton将的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 19:20