2011-02-06 70 views
0

有可能识别wht btn是否被一个唯一的eventListener按下?什么按钮被按下java

我想这代码,但

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

由于没有工作,!

回答

1

你的代码是非常需要被重构。例如,你有一个JButton数组,为什么不是一个类似的ImageIcons数组,那么你可以摆脱所有那些块。

例如:

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

而且不要忘记我在你关于进一步重构包括创建Player类,一类卡,甲板类,一个游戏管理器等其他线程建议。 (1).getImage();如果我使用另一个数组像test1.setIcon(play1Icons [i]);如何我可以定义这个问题,“我在这个脚本中有play1a = hand.get(1).getImage变量?”

手是一个ArrayList?解决这个问题的一种方法是做类似

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

或者其上的一些变体。

5

使用ActionEvent对象中的getSource方法。

你的代码是这样:

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

得到事件(即按下的按钮)的来源。上述

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

+0

所以你会得到 如果(arraybtn [1] .equals(e.getSource())):-) – hauntsaninja 2011-02-06 16:45:12

+0

谢谢,完美 – anvd 2011-02-06 16:46:59