是否可以在初始化后更改JPanel的图像?
Block.java(改变img的JPanel)
@SuppressWarnings("serial")
public class Block extends JPanel{
private int rotation;
public Block(){
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(Images.greenBlock, 0, 0, null);
}
}
现在我需要像changeImage
:
...
JPanel xy = new Block();
xy.changeImage(newImg); //I know this method does NOT exist
感谢您的帮助
答案 0 :(得分:2)
改变这个:
JPanel xy = new Block();
到此:
Block xy = new Block();
并使用Block changeImage(newImg)
方法更改变量greenBlock引用的图像。在您的changeImage方法中,不要忘记致电repaint();
问题:为什么paintComponent方法中的break;
语句?
如,
public class Block extends JPanel{
private int rotation;
// if you wish to initialize it with greenBlock...
private Image myImage = Images.greenBlock;
public Block(){
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(myImage, 0, 0, null);
}
public void changeImage(Image img) {
this.myImage = img;
repaint();
}
}