2010-10-29 15 views
7

Come inserire lo sfondo dell'immagine su JPANEL?JPanel con sfondo immagine

JPanel pDraw = new JPanel(new GridLayout(ROWS,COLS,2,2)); 
pDraw.setPreferredSize(new Dimension(600,600)); //size of the JPanel 
pDraw.setBackground(Color.RED); //How can I change the background from red color to image? 
+0

vorrei usare un [JImagePanel] (https://github.com/dberm22/DBoard/blob/master/src/com/dberm22/utils/ JImagePanel.java). Dovresti fare tutto il necessario per, – dberm22

risposta

2

Here's una spiegazione.

+0

Grazie per il tuo aiuto :) – Jessy

4

È 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); 
} 
+0

grazie Reese – Jessy