简体   繁体   中英

what button is pressed java

there is possible to recognize whst btn is pressed with a unique eventListener?

i tried this code, but didn't work

 ActionListener one = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if (gr1.getCounter1() < 5) {
                        gr1.setCounter1(gr1.getCounter1() + 1);
                        if (arraybtn[1].isSelected())
                            test1.setIcon(play1a);
                        if (arraybtn[2].isSelected())
                            test1.setIcon(play1b);
                        if (arraybtn[3].isSelected())
                            test1.setIcon(play1c);
                        if (arraybtn[4].isSelected())
                            test1.setIcon(play1d);
                        if (arraybtn[5].isSelected())
                            test1.setIcon(play1e);
                    } else {
                        pn5.setText("No more cards");
                    }
                }
            };

thanks, !

use the getSource method from the ActionEvent object.

Your code would look like:

if (e.getSource() == arraybtn[1])
   test1.setIcon(play1a);
if (e.getSource() == arraybtn[2])
   test1.setIcon(play1b);
if (e.getSource() == arraybtn[3])
   test1.setIcon(play1c);
if (e.getSource() == arraybtn[4])
   test1.setIcon(play1d);
if (e.getSource() == arraybtn[5])
   test1.setIcon(play1e);

to get the source of the event (ie the button that was pressed).

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

Your code above is in great need of being refactored. For instance you have an array of JButtons, why not a similar array of ImageIcons, then you could get rid of all those if blocks.

For instance:

  ActionListener one = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
        if (gr1.getCounter1() < 5) {
           gr1.setCounter1(gr1.getCounter1() + 1);
           for (int i = 0; i < arraybtn.length; i++) {
              if (arraybtn[i] == e.getSource()) {
                 test1.setIcon(play1Icons[i]);
              }
           }
        } else {
           pn5.setText("No more cards");
        }
     }
  };

And don't forget my recommendation in your other thread about further refactoring including creating a Player class, a Card class, a Deck class, a GameManager and so forth.

Regarding your question, "in this script i have play1a = hand.get(1).getImage(); if i do with another array like test1.setIcon(play1Icons[i]);, how i can define the variable?"

Is hand an ArrayList? One way to solve it is to do something like

test1.setIcon(hand.get(i).getImage()); 

or some variant on that.

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