2013-03-03 6 views
6

Sto provando a impostare un'icona su una JLabel da una cartella di immagini ogni volta che un elemento viene selezionato da un JComboBox. Il nome degli elementi in JComboBox e il nome delle immagini nella cartella sono gli stessi. Pertanto, ogni volta che un elemento viene selezionato da JComboBox, l'immagine corrispondente con lo stesso nome deve essere impostata come icona su JLabel. Sto cercando di fare qualcosa di simile.Come impostare Icon su una JLabel da un'immagine da una cartella?

private void cmb_movieselectPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt){                
     updateLabel(cmb_moviename.getSelectedItem().toString()); 
} 





protected void updateLabel(String name) { 
     ImageIcon icon = createImageIcon("C:\\Users\\xerof_000\\Pictures\\tmspictures\\" + name + ".jpg"); 
     if(icon != null){ 
      Image img = icon.getImage(); 
      Image newimg = img.getScaledInstance(lbl_pic.getWidth(), lbl_pic.getHeight(), java.awt.Image.SCALE_SMOOTH); 
      icon = new ImageIcon(newimg); 
      lbl_pic.setIcon(icon); 
      lbl_pic.setText(null); 
     } 
     else{ 
      lbl_pic.setText("Image not found"); 
      lbl_pic.setIcon(null); 
     } 
    } 





protected static ImageIcon createImageIcon(String path) { 
     URL imgURL; 
     imgURL = NowShowing.class.getResource(path); 
     if (imgURL != null) { 
      return new ImageIcon(imgURL); 
     } else { 
      return null; 
     } 
    } 

ho pensato che il problema è in "C: \ Users \ xerof_000 \ Immagini \ tmspictures \" Ho provato ad utilizzare "C:/Users/xerof_000/Immagini/tmspictures /", ma anche questo non ha funzionato. E qualunque cosa faccia, mostra solo "Immagine non trovata" su JLabel.

+2

Si prega di dare un'occhiata a questa risposta di mio, per come [aggiungere le immagini nella cartella risorsa] (http://stackoverflow.com/a/9866659/1057230), che la forza sarà di qualche aiuto sull'argomento :-) L'ultimo collegamento ti guiderà sicuramente, se fai tutto manualmente senza utilizzare alcun IDE. Se qualcosa non è ancora chiaro, si prega di chiedere :-) –

+1

Perché fare qualcosa di così complicato quando si tratta di 'nuovo ImageIcon (" C: \\ Users \\ xerof_000 \\ Pictures \\ tmspictures \\ "+ name +" .jpg ") ; 'funzionerà immediatamente? (Anche se questo non è molto mantenibile in quanto funzionerà solo sul tuo computer, sono d'accordo). –

+0

@GagandeepBali Lo sto facendo da NetBeans quindi ho controllato il collegamento NetBeans. Il fatto è che sto aggiungendo anche delle immagini alla cartella delle immagini durante il runtime del file .jar.E non posso aggiungere immagini al pacchetto nel file .jar mentre eseguo il file .jar non posso? Quindi c'è un modo per leggere le immagini da una cartella in cui viene eseguito il file .jar? –

risposta

12

Questa è la mia struttura di directory:

       packageexample 
             | 
        ------------------------------------------- 
        |     |      | 
       build(folder)  src(folder)   manifest.txt 
        |     | 
      swing(package)  ComboExample.java 
        | 
      imagetest(subpackage) 
        | 
    ComboExample.class + related .class files 

Questo è il contenuto del file ComboExample.java:

package swing.imagetest;  

import java.awt.*; 
import java.awt.event.*; 
import java.net.*; 
import javax.swing.*; 
     
public class ComboExample { 

    private String[] data = new String[]{ 
              "geek0", 
              "geek1", 
              "geek2", 
              "geek3", 
              "geek4" 
             }; 
    private String MESSAGE = "No Image to display yet..."; 
    private JLabel imageLabel; 
    private JComboBox cBox; 
    private ActionListener comboActions =  
          new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent ae) { 
      JComboBox combo = (JComboBox) ae.getSource(); 
      ImageIcon image = new ImageIcon(
         getClass().getResource(
          "/" + combo.getSelectedItem() + ".gif")); 
      if (image != null) { 
       imageLabel.setIcon(image); 
       imageLabel.setText(""); 
      } else { 
       imageLabel.setText(MESSAGE); 
      } 
     }     
    }; 

    private void displayGUI() { 
     JFrame frame = new JFrame("Combo Example"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 

     JPanel contentPane = new JPanel(); 
     imageLabel = new JLabel(MESSAGE, JLabel.CENTER); 
     cBox = new JComboBox(data); 
     cBox.addActionListener(comboActions); 

     contentPane.add(imageLabel); 
     contentPane.add(cBox); 

     frame.setContentPane(contentPane); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String... args) { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       new ComboExample().displayGUI(); 
      } 
     }); 
    } 
} 

ORA LA COMPILATION:

A co mpile ho fatto questo:

Gagandeep [email protected] ~/c/Mine/JAVA/J2SE/src/packageexample 
$ javac -d build src/*.java 

il contenuto del file manifesto:

enter image description here

JAR creazione del file:

Gagandeep [email protected] ~/c/Mine/JAVA/J2SE/src/packageexample 
$ cd build 

Gagandeep [email protected] ~/c/Mine/JAVA/J2SE/src/packageexample/build 
$ jar -cfm imagecombo.jar ../manifest.txt * 

Ora prendete questo JAR File in qualsiasi posizione avendo queste immagini (geek0.gif, geek1.gif, geek2.gif, geek3.gif e geek4.gif), ed eseguire il JAR File, e vedere i risultati :-)

+2

+1 Il [tutorial] (http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html) dovrebbe citare questa risposta! – trashgod

+1

Grazie mille :) mi ha aiutato molto. –

+0

Grazie a tutti e due a SORRIDERE :-) –

3

Come discusso in How to Use Icons, il metodo getResource() prevede di trovare l'immagine nel file JAR del programma. Avrai bisogno di spostare l'immagine nel tuo progetto. IconDemo è un esempio completo.

+0

quello era il modo in cui stavo facendo prima e funzionava. ma poi non sono in grado di aggiungere nuove immagini da leggere. come posso farlo leggere da una cartella specifica al di fuori del vaso in modo da poter aggiungere nuove immagini da leggere da quella cartella. –

+0

Si potrebbe provare un [_file URI_] (http://en.wikipedia.org/wiki/File_URI_scheme#Windows) o "nuovo ImageIcon (percorso)". – trashgod

0

Dal momento che si utilizza JLabel, è possibile utilizzare semplici tag HTML, basta iniziare il testo dell'etichetta con < html> e l'uso Tag HTML nell'etichetta come vuoi, in caso di tour: < img src = filepth \ imagefile.jpg> U può utilizzare questo per sostituire:). Con l'icona del sorriso.

0
 /* 

Create an Image File whose size is 700 x 472 (pixels) in any image editor. 
Here Image was created using MS - Paint. 

Make sure that the Image File and the main file are in the same folder. 

The size of the JFrame should be set to 700 x 472 (pixels) in the program. 


Set the JLabel's IconImage. 

Add the JLabel to the JFrame. 

Set JFrame properties. 

Display JFrame. 

------------------------------------------------------------------------------ 

label.setIcon(getClass().getResources(String name)); 

label.setIcon(new ImageIcon(String file)); 


These 2 methods, don't always work with us. 


So, we create a method "getImageIcon(File f)" that returns a new ImageIcon Object, 
everytime a new File Object is passed to it. 


*/ 




import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JButton; 


import java.awt.Image; 
import javax.imageio.ImageIO; 
import java.io.File; 
import java.io.IOException; 


import javax.swing.ImageIcon; 

import static javax.swing.WindowConstants.*; 






public class ImageDemo 
{ 

    JFrame frame = new JFrame();  //initialized 


    JLabel label = new JLabel();  //initialized 


    JButton button = new JButton(); //initialized 


    ImageIcon ii;    //not initialized 





    public void displayImage() 
    { 

     //Layout Type: Null Layout. 

     label.setIcon(getImageIcon(new File("print.png"))); 


     button.setBounds(150,150,358,66); 
     //Note that sizes of the Image and Button are same. 
     button.setIcon(getImageIcon(new File("Button.png"))); 



     label.add(button); 
     //add the button to the label 


     frame.add(label); 
     frame.setBounds(300, 50, 700, 472); 
     //(300 x 50 = HorizontalAlignment x VerticalAlignment) 
     //(700 x 472 = Width x Height)  

     frame.setTitle("Image Demo"); 
     frame.setDefaultCloseOperation(EXIT_ON_CLOSE); //WindowConstants.EXIT_ON_CLOSE 
     frame.setVisible(true); 


    } 





    public ImageIcon getImageIcon(File f) 
    { 


     try 
     { 
      Image im = ImageIO.read(f); 


      ii = new ImageIcon(im); 


     } 
     catch(IOException i) 
     { 

      i.printStackTrace(); 


     } 



     finally 
     { 

      return ii; 

     } 


    } 



    public static void main(String[] args) 
    { 

     ImageDemo id = new ImageDemo(); 

     id.displayImage(); 


    } 





} 
Problemi correlati