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

Répondre

26

Vous devez fournir au JLabel une implémentation Icon (c'est-à-dire ImageIcon). Vous pouvez le faire cuvette la méthode setIcon, comme dans votre question, ou par le constructeur JLabel:

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

je vous recommande de lire le Javadoc pour JLabel, Icon et ImageIcon. En outre, vous pouvez vérifier le How to Use Labels Tutorial pour plus d'informations.

23

Pour obtenir une image à partir d'une URL, nous pouvons utiliser le code suivant:

ImageIcon imgThisImg = new ImageIcon(PicURL)); 

jLabel2.setIcon(imgThisImg); 

Il fonctionne tout à fait pour moi. Le PicUrl est une variable de chaîne qui strore l'URL de l'image.

11

(Si vous utilisez l'EDI NetBeans) Créez simplement un dossier dans votre projet mais à l'extérieur du dossier src. Nommé le dossier Images. Et puis placez l'image dans le dossier Images et écrivez le code ci-dessous.

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

Maintenant, exécutez votre programme.

1

Le code simple que vous pouvez écrire dans main (String [] args) fonction

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

le plus court code est:

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

stringPictureURL est PATH de image