How do you reference a button inside of its actionlistener?

怎甘沉沦 提交于 2019-12-13 02:32:57

问题


I'm just starting to get used to listeners but I am still kind of new to working with them. I need to reference a button inside of its actionlistener to get the text of that button. my code I want is:

for(int i = 0; i<48; ++i){
        button[i] = new JButton("");
        contentPane.add(button[i]);
        button[i].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                x_marks_the_spot();
                if(button[i].getText().equals("X")){
                    increase_hit();
                }
                else{
                    increase_miss();
                }
            }
        });

Obviously I can't do this because [i] doesn't actually exist in the anon portion of code. I am sure there is a way to do this by getting the source, but I can't think of it.


回答1:


Obviously I can't do this because [i] doesn't actually exist in the anon portion of code.

You could do it by copying i into a final variable:

// Make a final copy of loop variable before making the listener
final tmpI = i;
...
// Use your final variable instead of `i` inside the listener
if(button[tmpI].getText().equals("X")){

However, this is not the most efficient way of doing it, because each button would need its own listener object, with the reference to tmpI stored inside the code.

You can create a single ActionListener object, and share it among all buttons, like this:

ActionListener listener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        x_marks_the_spot();
        JButton sender = (JButton)e.getSource();
        if(sender.getText().equals("X")){
            increase_hit();
        } else{
            increase_miss();
        }
    }
};
for(int i = 0; i<48; ++i){
    button[i] = new JButton("");
    contentPane.add(button[i]);
    button[i].addActionListener(listener);
}



回答2:


do this by getting the source

I believe what you want is ActionEvent.getSource()



来源:https://stackoverflow.com/questions/30928623/how-do-you-reference-a-button-inside-of-its-actionlistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!