Java – redraws jpanels with different images each time you click
I'm still a novice in Java. I have the following questions
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,this);}
else if(s==false){
g.drawImage(img2,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
Solution
Java is always passed by value, so your click method does not change the Boolean field of the class:
public void click(boolean s,boolean b){
s = b; // this does not change the class field s.
repaint();
}
The reason is that the S parameter above is different from the s field of the class, but the parameter implements the so-called "shadow" class field The solution is to change this method and delete the S parameter Or better - get rid of it completely
Note that if this is my application, I will use jlabel, give it a mouselistener, and simply swap imageicons on mousePressed
Your Boolean switching method:
public void mouseClicked(MouseEvent e){
if(s==true){
click(s,false);
}
else if(s==false){
click(s,true);
}
}
By doing so and getting rid of the wrong click (...) method, you can greatly simplify and correct:
public void mouseClicked(MouseEvent e){
s = !s;
repaint();
}
By the way, if (s = = true) is unnecessarily redundant If you need such a structure, you can do if (s) more concisely and simply The same applies to if (s = = false), better expressed as (! S)
