Volevo inserire un immagine di sfondo ad un JPanel. Su internet ho trovato consigli che mi hanno portato ad usare una classe apposita che estende JPanel e caricare quindi le URL delle immagini da costruttore.
Il codice nel costruttore è questo:
Codice PHP:
public void setContentPanel() throws MalformedURLException, IOException {
contentpanel = new JPanel();
imageURL1 = new URL ("http://farm4.static.flickr.com/3058/3067333469_3efd0073a9_o.jpg");
image_base1 = ImageIO.read(imageURL1);
contentnorthpanel = new BackgroundedPanel(image_base1);
imageURL2 = new URL ("http://farm4.static.flickr.com/3054/3068170810_d347ceda49_o.jpg");
image_base2 = ImageIO.read(imageURL2);
contentcenterpanel = new BackgroundedPanel(image_base2);
imageURL3 = new URL ("http://farm4.static.flickr.com/3035/3067333539_ed21a00770_o.jpg");
image_base3 = ImageIO.read(imageURL3);
contentsouthpanel = new BackgroundedPanel(image_base3);
contentpanel.add(contentnorthpanel);
contentpanel.add(contentcenterpanel);
contentpanel.add(contentsouthpanel);
}
Mentre la classe che serve per elaborare le immagini è la seguente:
Codice PHP:
package facesgame.image;
import java.awt.*;
import javax.swing.JPanel;
public class BackgroundedPanel extends JPanel {
private Image img;
public BackgroundedPanel(Image img) {
this.img = img;
}
@Override
public void paintComponent(Graphics g) {
Dimension panelSize = getSize();
int width = img.getWidth (this);
int height = img.getHeight (this);
for (int y = 0; y < panelSize.height; y += height) {
for (int x = 0; x < panelSize.width; x += width) {
g.drawImage (img, x, y, this);
}
}
}
}
Il programma non da errori di nessun genere, ma in runtime NON mostra le immagini... cosa posso fare?!
PS. Dato che ho intenzione di cambiare le immagini con un click su bottone... questo metodo va bene o mi conviene usare qualcos'altro che abbia un setXXX (setImageIcon, o simili, per es.)?
Grazie a tutti!!!!!!!!!