如何更改JPanel的背景图片
How to change background image of JPanel
是否可以在初始化后更改 JPanel 的图像?
Block.java (JPanel 改img)
@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
感谢您的帮助
改变这个:
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();
}
}
是否可以在初始化后更改 JPanel 的图像?
Block.java (JPanel 改img)
@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
感谢您的帮助
改变这个:
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();
}
}