根据鼠标单击的x,y动态更改JLabel图标

时间:2011-10-23 15:27:51

标签: java swing jlabel

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

/**
 * 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;
}

提前感谢您的帮助。这让我在过去两天疯狂

1 个答案:

答案 0 :(得分:2)

  

我不想为每个JLabel添加一个鼠标侦听器,然后复制并粘贴每个JLabel的代码。

您不必创建单独的侦听器。您可以与每个JLabel共享同一个侦听器。基本代码是:

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