[英]How to change background image of JPanel
初始化后是否可以更改 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
感謝您的幫助
改變這個:
JPanel xy = new Block();
對此:
Block xy = new Block();
並給 Block 一個changeImage(newImg)
方法,您可以在其中更改變量 greenBlock 所指的圖像。 在您的 changeImage 方法中,不要忘記調用repaint();
問題:為什么要break;
您的paintComponent 方法中的聲明?
例如,
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.