I’m still very new to Java and I have the following problem.
As you can see below I’ve created a JPanel with an image that I want to change whenever I click on the panel, but It doesn’t work for some reason. I’ve been sitting on it for hours now and seem to be completely stuck. If you could take a look at the code and help me I would be very grateful.
Thank you and have a nice Christmas.
public class Level {
JPanel panel
String img1Path = "img1.png";
String img2Path = "img2.png";
Image img1 = Toolkit.getDefaultToolkit().getImage(img1Path);
Image img2 = Toolkit.getDefaultToolkit().getImage(img2Path);
boolean s1 = false;
public Level(){
initGUI();
}
public void initGUI(){
panel = new JPanel(){
public void paintComponent(Graphics g){
super.paintComponent(g);
draw(g,s1);
}
}
panel.addMouseListener(new ImgListener(s1));
}
public void draw(Graphics g, boolean s){
if(s==true){
g.drawImage(img1,0,0,this);}
else if(s==false){
g.drawImage(img2,0,0,this);}
}//draw()
public void click(boolean s, boolean b){
s = b;
repaint();
}
public class ImgListener extends MouseAdapter {
boolean s;
public ImgListener(boolean s){
pS(s);
}
public void mouseClicked(MouseEvent e){
if(s==true){
click(s,false);
}
else if(s==false){
click(s,true);
}
}//mouseClicked
public void pS(boolean s){
this.s = s;
}//pS
}//ImgListener
}//Level
Java is pass-by-value always, and so your click method will not change your class’s boolean field:
The reason is the
sparameter above is not the same as the class’ssfield, but instead the parameter does what is known as “shadows” the class field. A solution is to change this method and get rid of the s parameter. Or better — get rid of the method entirely.Note that if this were my application, I’d use a JLabel, give it a MouseListener, and simply swap ImageIcons on mousePressed.
Also your boolean toggle method:
can be greatly simplified and corrected by doing this and getting rid of the erroneous click(…) method:
As an aside,
if (s == true)is unnecessarily redundant. If you need a construct like this, you can more succinctly and simply doif (s). Same forif (s == false)which is better represented asif (!s)