我对 Java 还是很陌生,我有以下问题。正如您在下面看到的,我创建了一个带有图像的 JPanel,每当我单击面板时我想更改该图像,但由于某种原因它不起作用。我已经坐在上面几个小时了,似乎完全被卡住了。如果您能看一下代码并帮助我,我将不胜感激。谢谢你,圣诞快乐。
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