Displaying new image in JLabel:

Hello,
I wondered if anyone could advise, how to display a new image into an Jlabel which already contains an image.
I used the this line to display the orginal image.
imageLabel = new JLabel(new ImageIcon("test.jpg"));
Thanks

This works for me:import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class HFrame extends JFrame implements ActionListener{
     private javax.swing.JPanel jContentPane = null;
     private javax.swing.JLabel jLabel = null;
     private javax.swing.JButton jButton = null;
     public HFrame(String title){
          super(title);
          initialize();
     private void initialize() {
          this.setSize(300, 200);
          this.setContentPane(getJContentPane());
          setDefaultCloseOperation(DISPOSE_ON_CLOSE);
     private javax.swing.JPanel getJContentPane() {
          if (jContentPane == null) {
               jContentPane = new javax.swing.JPanel();
               jContentPane.setLayout(new java.awt.BorderLayout());
               jContentPane.add(getJLabel(), java.awt.BorderLayout.CENTER);
               jContentPane.add(getJButton(), java.awt.BorderLayout.NORTH);
          return jContentPane;
     public static void main(String[] args) {
          HFrame hf = new HFrame("Help");
          hf.setVisible(true);
     public void getPath(){
          FileDialog fd = new FileDialog(this,"Pick file", FileDialog.LOAD);
          fd.show();
          if (fd.getFile() == null) {
               return;
          String imagePath =  fd.getDirectory() + fd.getFile();
          System.out.println(imagePath);
          getJLabel().setIcon(new ImageIcon(imagePath));
     private javax.swing.JLabel getJLabel() {
          if(jLabel == null) {
               jLabel= new JLabel();
          return jLabel;
     private javax.swing.JButton getJButton() {
          if(jButton == null) {
               jButton = new javax.swing.JButton();
               jButton.setText("image");
               jButton.addActionListener(this);
          return jButton;
     public void actionPerformed(ActionEvent e) {
          getPath();
}

Similar Messages

  • Delay in displaying new images

    Here's the situation.
    Shooting tethered with a Nikon D800E. Using Nikon Camera Control Pro to operate the camera. Using Adobe Bridge CS6 to monitor the destination folder. There is often a delay before Bridge will display new images. For several exposures in a row Bridge will display new images as they are created. Eventually it get to the point where it will not display a new shot. When you take a second shot, both it and the preivious image will appear together. Some times two shots in a row will not apprear and upon taking a third shot all three will apprear. I've tried switching thumbnail options, Prefer Embedded, On Demand, HQ, it's a little more responsive when using the embeded thumnail but still has the issue.
    I've tried two workstations. A MacPro 3.1 running OSX 10.6.8 and a Mini 6.2 running 10.8.3. Bridge has the same problem on both some what worse on the Mini.
    Has anyone seen this problem when monitoring a folder that is activly receiving new images?
    On a side note, it would be great if Bridge would scroll to display new images. Seems like it would have to auto select the newest image.
    Thanks,
    David

    This is what I was thinking of.  He speaks specifically of signal delays.
    Helpful Equipment:
    16′ or 25′ USB Booster Extension Cable
    This is a must! Standard  USB camera connection cables are too short for practical work. Since  transfer speeds are slower over distance, typical USB extension cables  are a poor choice. An “active” USB extension cable or “booster”  cable is self powered through the connection, allows a cleaner signal,  decreases the risk of corrupted files, and maintains a steady download speed.  Active USB extension cables can be daisy chained up to 75.’
    IOGEAR USB Extension at Amazon

  • Problem in displaying images using JLabel in Netbeans

    hi all,
    i am trying to display an image on JLabel in Netbeans.The image is visible in the design view but not displayed in the runtime.Can anyone help me out with suggestions???

    Duplicate - answer here http://forum.java.sun.com/thread.jspa?threadID=5153605&messageID=9578626#9578626

  • Need help in displaying an Image in a JLabel

    Hi everyone,
    I am using a JLabel to display images on a particular screen. I am facing some problem while doing so..
    On my screen there are images of some garments. When the users select colors from a particular list, i should color this garment images and load it on the screen again with the colors. I have a floodfill class for filling the colors in the images. The problem I am facing is I am able to color the image properly with my floodfill class but when displaying the image on the same jlabel, the image gets distorted somehow.
    Everytime I color the image, I create an ImageIcon of the image and use the seticon method from the JLabel class. First I set the icon to null and then set it to the imageicon created. here is the code I use.
    If 'image' is the the image i have to load
    ImageIcon imgicon = new ImageIcon(image);
    jlabel.setIcon(null);
    jlabel.setIcon(imgicon);I am setting the icon to null because I have not found any other method to clear the previous image from the jlabel.
    Can anyone who has worked on images before and faced a similar situation help me with this?? Is there some other container I can use besides the JLabel to display the images perhaps?
    Thanks in advance.....
    Bharat

    And the thing is when I first go into that screen with the selected colors it is displaying the images perfectly.
    It is only giving problems when I pick different colors on the screenit really sounds like the problem is in your floodfill class.
    I have no idea what's in floodfill, but if you were e.g. using a JPanel and paintComponent,
    you would need to have as the first line in paintComponent()
    super.paintComponent(..);
    to clear the previous painting.
    if not, you would be just drawing over the top of the previous paintComponent(), and if the calculation of the
    painting area is not 100% exact, you may get the odd pixel not painted-over, meaning those pixels will display
    the old color.

  • Displaying image in jlabel

    when displaying an image in a jlable. the jlabel takes on the size of the image. i have tried to set the maximum bounds to the size of the original size of the jlable and even the panel the jlable sits on, but each time that i go to display the picture, it is displayed huge and not the size of the jlabel it is placed in.
    here is my creation code, my gui was created in netbeans.
    pnImage.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
            pnImage.setFocusable(false);
            pnImage.setMaximumSize(new java.awt.Dimension(395, 365));
            lblImage.setFocusable(false);
            lblImage.setMaximumSize(new java.awt.Dimension(395, 365));
            javax.swing.GroupLayout pnImageLayout = new javax.swing.GroupLayout(pnImage);
            pnImage.setLayout(pnImageLayout);
            pnImageLayout.setHorizontalGroup(
                pnImageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(lblImage, javax.swing.GroupLayout.PREFERRED_SIZE, 393, javax.swing.GroupLayout.PREFERRED_SIZE)
            pnImageLayout.setVerticalGroup(
                pnImageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(lblImage, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE)
            );and here is how i display it.
            Dimension d = pnImage.getSize();
            System.out.println("d = " + d.toString());
            pnImage.setMaximumSize(d);
            lblImage.setMaximumSize(d);
            ImageIcon icon = new ImageIcon(contact.getImage());
            lblImage.setIcon(icon);

    I've never done this (convert a byte array to an image), so I thought I'd have a go...import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    public class ImageTest {
        public static void main(String[] args) throws Exception {
                // Grab some image...
            File inFile = new File("resources/imageH.jpg");
            int len = (int)inFile.length();
            System.out.printf("file length = %d%n", len);
            FileInputStream in = new FileInputStream(inFile);
                // ... and create a byte array for testing
            byte[] byteArray = new byte[len];
            int num = in.read(byteArray);
            in.close();
            System.out.printf("bytes read = %d%n", num);
                // (1) Create an image from the byte array - I don't
                // know Imagio figures out what sort of image it is!
            BufferedImage im = ImageIO.read(new ByteArrayInputStream(byteArray));
            int w = im.getWidth();
            int h = im.getHeight();
            System.out.printf("width = %d, height = %d", w, h);
                // (2) Scale to fit 100x100
            if(w > h) {
                w = (100 * w) / h;
                h = 100;
            } else {
                h = (100 * h) / h;
                w = 100;
            System.out.printf(" --> %d,%d%n", w, h);
                // (3) And create the icon
            ImageIcon icon = new ImageIcon(im.getScaledInstance(w, h, Image.SCALE_SMOOTH));
            System.out.printf("The icon is: %s%n", icon);
    }The output isfile length = 54918
    bytes read = 54918
    width = 500, height = 300 --> 166,100
    The icon is: javax.swing.ImageIcon@5afd29Assuming your byte array is some (to ImageIO) recognisable image format, something
    similar should work for you.

  • Displaying Image using JLabel in swings

    I am not understanding how to display a image in swing using JLabel Component.
    I am writing in the following manner:
    // importing necessary packages
    in init() method
    public void init()
    Container cp= getContentPane()
    JLabel jl=new JLabel("Image",new ImageIcon("<image>.gif"),JLabel.CENTER);
    cp.add(jl);
    applet is running and only label msg is displaying but not the image.
    Please help me so that i can solve this problem.where the image is to be placed??and how it has to be included?
    Please provide me the solution.

    cp.add(new JLabel("Image",new ImageIcon(new java.net.URL (getCodeBase(),"Test.gif")),JLabel.CENTER));

  • HELP! how to display an image when clicking on JLabel?

    hi. new to the forums. anyway, i need help in displaying an image.
    what i'm trying to do is when clicking on a JLabel using mouseClicked, an image will show and when the image is clicked it will disappear. i've searched and searched and have not found anything useful. thanks...

    thanks.
    searched on the setIcon, didn't find anything. btw, i know how to set the icon on the JLabel. i'm trying to figure out how i can get it that when i click on the JLabel by using the mouseClicked (or maybe even mousePressed) listener, the image pops up and when i click on the image, it closes or disappears.
    btw, i'm using the netBeans GUI builder for this. thanks again.

  • Question about displaying image with JLabel

    Hi
    I need to display an image. The image is determined by the user at run time, so the dimension of the image is unknown. Is it possible for JLabel to stretch the image so the whole image(instead of only part of it) will always fits into a certain dimension?
    thanks.

    For this you need to create a custom class that extends ImageIcon
    and define the methods there.
    see Java Tutorial for it.
    For eg., to scale an image , you can use
    JLabel label = new JLabel();
    Image img = new ImageIcon("Pics/Ash.jpg").getImage();
    int width = img.getWidth(null);
    int height = img.getHeight(null);
    //This would scale the Image by 200%
    Image bimg = image.getScaledInstance(width*2, height*2, Image.SCALE_SMOOTH);
    label.setIcon(new ImageIcon(bimg));
    //There is also another way
    //Use drawImage and use BufferedImage
    BufferedImage buff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics g = buff.getGraphics();
    //Scale the Image to 200%
    g.drawImage(img, 0, 0, width*2, height*2,  null);
    lable.setIcon(new  ImageIcon(buff));Hope you get the idea!!

  • How do you display a new image in  webdynpro view?

    How do you display a new image in  webdynpro view?
    Where is the image stored and how do we specify the image path?

    hi ,
    The UI element Image enables you to integrate graphics into the Web application in a format that is processed by the Web Server u2013 for example, GIF, JPG, and PNG format. Height and width of the graphic can be specified using the properties height and width. The graphic is displayed without borders.
    saveur image   as mime
    with Mime Objects u cn upload doc , jpeg, or giff files from our local system into the webdypnpro system .
    Right click on ur component->mime object->import
    In the transaction sicf/bc/webdynpro , u cn check your component name there you can view the mime objects created by you .
    also refer the SAP online help :
    http://help.sap.com/saphelp_crm50/helpdata/en/46/bb182fab4811d4968100a0c94260a5/content.htm
    to knw more abt mime repositories.
    http://help.sap.com/saphelp_nw04/helpdata/en/f3/1a61a9dc7f2e4199458e964e76b4ba/content.htm
    regards,
    amit

  • How to display a rectangular ROI in a new image?

    Hi,
       I want to display a rectangular ROI in a new image. I want the rest of the image to be cropped.
    I selected the ROI by using the  'IMAQ Select Rectangle' vi And
     changed the rectangle output generated into an ROI using 'IMAQ Convert Rectangle to ROI' vi
    Is there a more easier way?
                     Thank you.

    I suppose you would have read laura's answer in this thread
    Hi Everyone,
    I am reporting the strange behavior that may be linked to the loading time for the editor.  I'll keep you updated as I hear updates.
    Thanks,
    Laura
    Ohla and editing works afterall but who cares if it takes a couple MINUTES!!!!
    Message Edited by muks on 08-30-2008 02:08 AM

  • Will aperture auto advance to display each new image when shooting tethered?

    I've tethered successfully with the Canon 6D using either Lightroom or Aperture. When using Lightroom, it will automatically load the new image for display on my external monitor. I cannot find a way to have the same result with Aperture and I would much prefer to use Aperture so the images can be imported directly into the Aperture library. Am I missing something or is this not possible? I like to work from the camera, not sitting at the computer. 

    Short answer: Yes.
    When you initiaite a thethered session, there is a checkbox in the tether HUD that turns auto-advance on or off. The default is on.
    If you have tried it and it doesn't work, what are the symptoms?

  • Display an image in a new window

    I am trying to display an image when certain criteria is met.  How can I either open the image to a new window jsut displaying the image or just have the image pop up in the window that is already open.
    Thanks

    A simple solution would be to use a case selection so that when you criteria has been met
    then a VI pops ups with image .
    Use an exit button to terminate VI(close ).
    chow
    xseadog

  • Problem setting a new image to be displayed in JScrollPane

    Hi everyone,
    I'm having a problem with an image retrieval application I'm developing and basically the problem is when I run the application and search for an image, the image is found and displayed fine on screen using an instance of DisplayJAI (from the JAI packages). However, when I search for another image it clears the old image fine but doesn't display the new one. I though it might be a repaint issue because the SQL is correct but it simply clears the scrollPane of content and doesn't update it with the new image. Has anyone ever come across this problem before or have any ideas? Any help would be much appreciated, thanks.

    This is fixed by turning off the optimization..

  • Can not display ImageIcon in a JLabel where you want in the code ???

    Hello, everybody. I need your help to solve a problem I am on it for 2 days now :
    In the constructor of my class, I have a lot of initializing methods. If I try to display an image (with ImageIcon in a JLabel) within one of these methods, there is no problem and the image is correctely displayed. To try that, I use an image stored on my local disk in "c:\\".
    public class Bedes extends javax.swing.JFrame {
    public Bedes() {
    initComponents();
    -- further initializations
    initConnection();
    public void initConnection() {
    try {
    String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
    Properties systemProperties = System.getProperties();
    systemProperties.put("jdbc.drivers", driverName);
    System.setProperties(systemProperties);
    String dbURL = "jdbc:odbc:Bandes Dessin�es";
    String strUtilisateur = "bedes";
    String strMotDePasse = "cdle";
    connectBedes = DriverManager.getConnection(dbURL,strUtilisateur,strMotDePasse);
    catch (Exception e) {
    System.out.println("Exception in DB Contact " + e);
    // Here, I display an image in my JLabel, and it works :
    couvertureAlbumString = "c:\\myImage.jpg";
    couvertureAlbumsIcon = new ImageIcon(couvertureAlbumString);
    couvertureAlbumsJLabel.setIcon(couvertureAlbumsIcon);
    couvertureAlbumsJLabel.repaint();
    }The problem is that I do not want to display these images there, but in a method that read some data's in a Database (with "try"-"catch" blocks). If there is a name of an image store in the DB, then it must be displayed in the JLabel (located in a JFrame -> JDeskTopPane -> JTabbedPane -> JPanel).
    private void searchDetailsForAlbum(String albumsDetailsToSearch) {
    String nomImageCouverture;
    String couvertureAlbumString;
    ImageIcon couvertureAlbumsIcon;
    try {
    PreparedStatement requeteDetailsAlbums = connectBedes.prepareStatement("SELECT * FROM bandes_dess WHERE bede_nom_tome = ?");
    requeteDetailsAlbums.setString(1, albumsDetailsToSearch);
    ResultSet resultatDetailsAlbums = requeteDetailsAlbums.executeQuery();
    resultatDetailsAlbums.next();
    collectionAlbumsJTextField.setText(resultatDetailsAlbums.getString(6));
    genreAlbumsJTextField.setText(resultatDetailsAlbums.getString(9));
    dessinateurAlbumsJTextField.setText(resultatDetailsAlbums.getString(10));
    scenaristeAlbumsJTextField.setText(resultatDetailsAlbums.getString(11));
    coloristeAlbumsJTextField.setText(resultatDetailsAlbums.getString(12));
    prixAchatAlbumsJTextField.setText(resultatDetailsAlbums.getString(13));
    // Here is the name of the Image to de read
    nomImageCouverture = resultatDetailsAlbums.getString(14);
    catch (Exception e) {
    System.out.println("Exception in searchDetailsForAlbum" + e);
    couvertureAlbumString = "c:\\";
    // Here, I check if there is a name for a picture in the DB
    if (!(nomImageCouverture.equals("No"))) {
    // If Yes, I want to display it
    couvertureAlbumString = couvertureAlbumString + nomImageCouverture;
    couvertureAlbumsIcon = new ImageIcon(couvertureAlbumString);
    couvertureAlbumsJLabel.setIcon(couvertureAlbumsIcon);
    couvertureAlbumsJLabel.repaint();
    }My JLabel is well displayed, but empty, without any image on it. WHY ???
    MLK, you asked me to add some debug code. OK, with pleasure, but what is that "debug code" ???
    Thanks a lot in advance if you could help me.
    Christian.

    DEBUG: couvertureAlbumString: c:\Aldebaran-La-Photo
    OK, the extension of the file was NOT present !!!
    I added it and ..... it works pretty good !!!
    Thank you for your idea of the DEBUG.
    Christian.

  • Displaying an image from a URL

    I have a program which visits a html page and creates a JComboBox with all the images from that page. When the user selects an image from the combo box it displays that image in a JLabel. This works fine with images that exist, when I try it with an image that doesn't exist I want it to realise that and display a message saying that "the image cannot be found". Heres part of my code that handles the selection:
    public void actionPerformed(ActionEvent f) {
                        JComboBox cb = (JComboBox)f.getSource();
                        String imageName = (String)cb.getSelectedItem();
                        try {
                             imageUrl = new URL(imageName);
                        catch (MalformedURLException ex) {
                             System.out.println("Image Collection Error: " + ex);
                        catch (Exception e) {
                             System.out.println("Some sort of exception: " + e);
                        picture.setIcon(new ImageIcon(imageUrl));
              });When I select a bad link image from the list I was hoping the catch blocks would trap it and I could make adjustments accordingly, this does not happen. No exception is thrown at all.
    Any ideas of what I can do??
    Bow_wow.

    Thanks for your help, I have changed it to the following code:
    ImageIcon imageToDisplay = new ImageIcon(imageUrl);
                        ImageIcon badImage = new ImageIcon("logo.jpg"); // An image I know exists
                        int status = imageToDisplay.getImageLoadStatus();
                        if (status == MediaTracker.COMPLETE) {
                             picture.setIcon(imageToDisplay);
                        else {
                             picture.setIcon(badImage);                              
                        }It works now, thanks again for your help!

Maybe you are looking for

  • Firefox 4 freezes when I try to clear 1 hour of history. Why?

    WinXP SP3, Firefox 4.0.1 When I try to clear the last hour of History, Firefox freezes and will not respond no matter how long I wait for it. Before Firefox 4, it might take as along as two minutes. Back in version 3.6, it only took a few seconds.

  • Connecting mac book to tv to watch movies

    What cords/ connections do I need to set up my computer to a panasonic viera. I am in Switz and do not have any any english tv, it would be great to watch the movies on my computer. Thanks for any help.

  • How do you tell if your iphone has been hacked?

    How do you tell if you iphone has been hacked? I have an iphone 3GS and I've gotten text messages from 2 different people that i don't know, telling me they can't see the pics that I've sent them & wanting to know what the pics are of. One of the num

  • Problem with printing from Powerpoint 2007

    Am printing to pdf from Powerpoint 2007 (using Acrobat 8.1.4), using the Print>Select Printer>Adobe PDF route, but the pdfs that are being created look terrible (distorted, washed out colours, etc) and print even worse. Is there an incompatibility pr

  • PSE 11 won't open files

    When I try to open afile with Pse 11 I get an error message that says file is locked or I don't have permissions. I did find that files were marked as read only but changing it doesn't seem to  change things. I have full pemissions to edit these file