I am using NETBEANS and have several JLabels that need to display a specific icon/image based on a decision/boolean. I do not want to have to add a mouse listener for every JLabel and then copy and paste the code for each one. Rather I would prefer to use the x,y as the name of the JLabel and then set icon based on the x,y. I have no problems getting the x.y but cannot seem to figure out how to do something like this (xy.setIcon(new ImageIcon(Hit)); here is my code.
/**
* 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;
}
Thank you in advance for all your help. This has been driving me crazy for the last two days