2011-10-23 160 views
1

我正在使用NETBEANS,并且有几个JLabel需要根据决策/布尔值显示特定的图标/图像。我不想为每个JLabel添加一个鼠标侦听器,然后复制并粘贴每个JLabel的代码。相反,我宁愿使用x,y作为JLabel的名称,然后根据x,y设置图标。我没有问题得到XY,但似乎无法弄清楚如何做这样的事情(xy.setIcon(新的ImageIcon(打));这里是我的代码根据鼠标点击的x,y动态更改JLabel图标

/** 
* Mathematical coordinates of player1Fleet. 
* Used to realign ships from Ship Class 
* for use on game board. 
*/ 
public void mouseClicked(MouseEvent e) { 
    Launch1(); 
} 
public void FleetP1() { 
    for (Ship s : player1Fleet) { 
     int size = s.getSize(); 

     for (int i = 0; i < size; i++) { 
      player1Ships.add((((s.getXCoordinate(i) + 1) * 45) + 90) + "" + (((s.getYCoordinate(i) + 1) * 45) + 180)); 

     } 
    } 
    // Verification of Math 
    System.out.println(player1Ships); 
} 

/** 
* Determine Hit or Miss based on location of Cross-hairs 
* for player 1/West on game board. 
* @return 
*/ 
//public boolean setStrike1(){ 
public boolean Launch1() { 
    w93.setIcon(null); 
    player1Ships.clear(); 
    FleetP1(); 
    boolean strike1 = false; 
    boolean Launch = false; 
    for (int i = 0; i < this.player1Ships.size(); i++) { 
     if (this.player1Ships.get(i).equals(LblCrossHairs.getX() + "" + LblCrossHairs.getY())) { 
      strike1 = true; 
      //break; 
     } 
     if (strike1) { 
      strike1 = true; 
      (LblCrossHairs.getX() + "" + LblCrossHairs.getY()).setIcon(new ImageIcon(Hit)); 
      //Launch = theAttack.Strike1(strike1); 
      //w93.setIcon(new ImageIcon(Hit)); 
      URL url = this.getClass().getResource("MissleHit.au"); 
      AudioClip ac = Applet.newAudioClip(url); 
      ac.play(); 
      System.out.println("HIT"); 
      break; 
     } else { 
      strike1 = false; 
      (LblCrossHairs.getX() + "" + LblCrossHairs.getY()).setIcon(new ImageIcon(Hit)); 
      //w93.setIcon(new ImageIcon(Miss)); 
      URL url = this.getClass().getResource("MissileMiss.au"); 
      AudioClip ac = Applet.newAudioClip(url); 
      ac.play(); 
      System.out.println("MISS"); 
     } 
    } 
    TxtClick.setText(LblCrossHairs.getX() + "" + LblCrossHairs.getY() + ".setIcon"); 
    return strike1; 
} 

预先感谢您为您的所有帮忙。这已经快把我逼疯了最后两天

+2

你的*问题是什么?*为了更好地帮助,请发布[SSCCE](http://sscce.org/)。 –

回答

2

我不希望有添加一个鼠标监听,每一个JLabel,然后复制并粘贴代码,为每一个。

你不必创建一个单独的监听器,你可以与ev共享同一个监听器JLabel。基本代码是:

public void mouseClicked(MouseEvent e) 
{ 
    JLabel label = (JLabel)e.getSource(); 
    label.setIcon(...); 
} 
public void mouseClicked(MouseEvent e) 
{ 
    JLabel label = (JLabel)e.getSource(); 
    label.setIcon(...); 
} 
+0

+1正确;有一个相关的例子[这里](http://stackoverflow.com/questions/5136859/mouselistener-help-java/5137250#5137250)。 – trashgod

+0

除非我希望在Launch1方法中使用它,并且当我使用它时,会出现错误。找不到符号Symbol:Variable e Location:Class game.GUI如果执行以下操作; public boolean Launch1(标签e)我只为标签获得相同的错误。 – user1009629

+0

因此,将标签作为参数传递给Launch1(...)方法。 – camickr