È probabilmente più facile per caricare il Image
in un ImageIcon
e visualizzarli in un JLabel
, però:
A direttamente 'disegnare' l'immagine al JPanel, sovrascrivere il metodo del JPanel paintComponent(Graphics)
a qualcosa di simile al seguente:
public void paintComponent(Graphics page)
{
super.paintComponent(page);
page.drawImage(img, 0, 0, null);
}
dove img
è un Image
(eventualmente caricati tramite la chiamata ImageIO.read()
).
Graphics#drawImage
è un comando molto sovraccarico che ti consentirà di essere molto specifico su come, quanto e dove dipingi l'immagine sul componente.
È inoltre possibile ottenere "fantasia" e ridimensionare l'immagine a piacere utilizzando il metodo Image#getScaledInstance
. Ciò richiederà un -1
per il parametro width
o height
per mantenere lo stesso rapporto di aspetto dell'immagine.
dirla in modo più fantasia:
public void paintComponent(Graphics page)
{
super.paintComponent(page);
int h = img.getHeight(null);
int w = img.getWidth(null);
// Scale Horizontally:
if (w > this.getWidth())
{
img = img.getScaledInstance(getWidth(), -1, Image.SCALE_DEFAULT);
h = img.getHeight(null);
}
// Scale Vertically:
if (h > this.getHeight())
{
img = img.getScaledInstance(-1, getHeight(), Image.SCALE_DEFAULT);
}
// Center Images
int x = (getWidth() - img.getWidth(null))/2;
int y = (getHeight() - img.getHeight(null))/2;
// Draw it
page.drawImage(img, x, y, null);
}
fonte
2010-10-29 12:12:21
vorrei usare un [JImagePanel] (https://github.com/dberm22/DBoard/blob/master/src/com/dberm22/utils/ JImagePanel.java). Dovresti fare tutto il necessario per, – dberm22