Ho un JPanel a cui vorrei aggiungere immagini JPEG e PNG che genero al volo.
Tutti gli esempi che ho visto finora nei Tutorial Swing, specialmente negli Esempi di Swing usano `ImageIcon's.
Sto generando queste immagini come array di byte, e di solito sono più grandi della comune icona che usano negli esempi, a 640x480.
Modifica: Un esame più attento dei tutorial e delle API mostra che non è possibile aggiungere un'ImageIcon direttamente ad un JPanel. Invece, si ottiene lo stesso effetto impostando l'immagine come icona di una JLabel. Questo non mi sembra giusto...
Ecco come lo faccio (con un po' più di informazioni su come caricare un'immagine):
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel() {
try {
image = ImageIO.read(new File("image name and path"));
} catch (IOException ex) {
// handle exception...
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this); // see javadoc for more info on the parameters
}
}
ImageIcon's. Per una singola immagine, penserei di fare una sottoclasse personalizzata di
JPanele sovrascrivere il suo metodo
paintComponent` per disegnare l'immagine.Puoi sottoclasse di JPanel - qui c'è un estratto del mio ImagePanel, che mette un'immagine in una qualsiasi delle 5 posizioni, in alto a sinistra, in alto a destra, al centro, in basso a sinistra o in basso a destra:
protected void paintComponent(Graphics gc) {
super.paintComponent(gc);
Dimension cs=getSize(); // component size
gc=gc.create();
gc.clipRect(insets.left,insets.top,(cs.width-insets.left-insets.right),(cs.height-insets.top-insets.bottom));
if(mmImage!=null) { gc.drawImage(mmImage,(((cs.width-mmSize.width)/2) +mmHrzShift),(((cs.height-mmSize.height)/2) +mmVrtShift),null); }
if(tlImage!=null) { gc.drawImage(tlImage,(insets.left +tlHrzShift),(insets.top +tlVrtShift),null); }
if(trImage!=null) { gc.drawImage(trImage,(cs.width-insets.right-trSize.width+trHrzShift),(insets.top +trVrtShift),null); }
if(blImage!=null) { gc.drawImage(blImage,(insets.left +blHrzShift),(cs.height-insets.bottom-blSize.height+blVrtShift),null); }
if(brImage!=null) { gc.drawImage(brImage,(cs.width-insets.right-brSize.width+brHrzShift),(cs.height-insets.bottom-brSize.height+brVrtShift),null); }
}