public class Example extends JPanel {
BufferedImage background;
public Example () {
background = loadImage();
}
private BufferedImage loadImage(){
URL imagePath = getClass().getResource("Immagini/Board.png");
BufferedImage result = null;
try {
result = ImageIO.read(imagePath);
} catch (IOException e) {
System.err.println("Errore, immagine non trovata");
}
return result;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension size = getSize();
g.drawImage(background, 0, 0,size.width, size.height,0, 0, background.getWidth(), background.getHeight(), null);
}
}
它很完美,现在我不能这样做,因为我的newExample类扩展了genericExample,因此也无法扩展JPanel。我在newExample中有JPanel panel = new JPanel()
,我想在上面的代码中绘制,我如何调整它以适应这种不同的情况?
答案 0 :(得分:1)
您仍然可以重复使用Example
课程。您将使用覆盖的面板类而不是JPanel panel = new JPanel();
:
JPanel panel = new Example();
另一种方法是使用JPanel
的匿名实现:
JPanel panel = new JPanel(){
BufferedImage background = loadImage();
private BufferedImage loadImage(){
URL imagePath = getClass().getResource("Immagini/Board.png");
BufferedImage result = null;
try {
result = ImageIO.read(imagePath);
} catch (IOException e) {
System.err.println("Errore, immagine non trovata");
}
return result;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension size = getSize();
g.drawImage(background, 0, 0,size.width, size.height,0, 0, background.getWidth(), background.getHeight(), null);
}
};
请注意,您无法在匿名类中使用构造函数,但这对于可重用性是不利的。
希望这有点帮助