2010-09-23 12 views
20
Image image = GenerateImage.toImage(true); //this generates an image file 
JLabel thumb = new JLabel(); 
thumb.setIcon(image) 

risposta

26

È necessario fornire a JLabel un'implementazione Icon (ad esempio ImageIcon). Si può fare esso attraverso il metodo setIcon, come nella tua domanda, o tramite il costruttore JLabel:

Image image=GenerateImage.toImage(true); //this generates an image file 
ImageIcon icon = new ImageIcon(image); 
JLabel thumb = new JLabel(); 
thumb.setIcon(icon); 

vi consiglio di leggere il Javadoc per JLabel, Icon e ImageIcon. Inoltre, è possibile controllare lo How to Use Labels Tutorial, per ulteriori informazioni.

23

per ottenere un'immagine da un URL possiamo utilizzare il seguente codice:

ImageIcon imgThisImg = new ImageIcon(PicURL)); 

jLabel2.setIcon(imgThisImg); 

Funziona tutto per me. PicUrl è una variabile stringa che strorizza l'URL dell'immagine.

11

(Se si utilizza NetBeans IDE) Basta creare una cartella nel progetto ma fuori dalla cartella src. Chiamato la cartella Immagini. E poi metti l'immagine nella cartella Immagini e scrivi il codice qui sotto.

// Import ImageIcon  
ImageIcon iconLogo = new ImageIcon("Images/YourCompanyLogo.png"); 
// In init() method write this code 
jLabelYourCompanyLogo.setIcon(iconLogo); 

Ora esegui il tuo programma.

1

semplice codice che si può scrivere in main (String [] args) funzione

JFrame frame = new JFrame(); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//application will be closed when you close frame 
    frame.setSize(800,600); 
    frame.setLocation(200,200); 

    JFileChooser fc = new JFileChooser(); 
    if(fc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION){ 
     BufferedImage img = ImageIO.read(fc.getSelectedFile());//it must be an image file, otherwise you'll get an exception 
     JLabel label = new JLabel(); 
     label.setIcon(new ImageIcon(img)); 
     frame.getContentPane().add(label); 
    } 

    frame.setVisible(true);//showing up the frame 
3

il codice più breve è:

JLabel jLabelObject = new JLabel(); 
jLabelObject.setIcon(new ImageIcon(stringPictureURL)); 

stringPictureURL è PATH di Immagine .