Images in jlabels

I am trying to put an image into a jlabel so that the image size is identical to the jlabel size, even if the image is not the same size i.e is there some code which will format the referenced image so that it fits perfectly into the jlabel without overlapping or being too small?
Any help would be much appreciated.

import java.awt.*;
import javax.swing.*;
public class Test2 extends JFrame {
  public Test2() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = getContentPane();
    content.add(new MyLabel(new ImageIcon("C:\\duke.gif").getImage()));
    setSize(300, 300);
    setVisible(true);
  public static void main(String args[]) { new Test2(); }
class MyLabel extends JLabel {
  Image image;
  public MyLabel(Image image) { this.image = image; }
  public void paintComponent(Graphics g) {
    g.fillRect(0,0,getWidth(),getHeight());
    g.drawImage(image,0,0,getWidth(),getHeight(),this);
}

Similar Messages

  • Changing images in JLabels

    I am creating a program which needs to display a grid of 7 by 7 images, as i am new to swing and fairly new to java i decided to use JLabels to show these images.
    I also need to be able to change these images, when buttons are clicked, i have set up the listeners for the buttons and the initial grid is correct however i cannot get the images to change?
    The JLabels are done as an array so each JLabel can be identified seperately.
    I have tried changing the labels eg Images=new JLabel("newimage.gif");
    and also I have tried creating other JLabels and doing things like
    Images[i]=newLabel //newLabel has the icon i want to use.
    I have repainting the screen and if i use the setText method on the JLabels then the text is displayed, however new images aren't
    do i need to not use JLabels, if so what can i use to do this?

    i tried using the setIcon function on my screen capture program and was unable to get it to update the image as long as the old image file was the same filename as the new image file. however if you change the image file name i got it to work fine......you just can't refresh an image of the same name if you've changed the content......

  • 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));

  • Images in jlabel

    hi,
    I found a problem in bringing out images in jlabel.
    thanks for peio for your sample code.
    I found an error "cannot resolve symbol"
    for frame.getContentPane().I extended JFrame in the
    class I implemented this init() method.
    getContentPane is working correctly when called simply.
    Being a UG student undertaking a training in java
    swings I have a little maturity in java bugs.
    please guide me.
    yours friendly,
    mohan raj

    ImageIcon caches the previously loaded images and won't reload an image from the same source. Unfortunately, this is not documented in the public API but only in the source of ImageIcon.java.public class ImageIcon implements Icon, Serializable, Accessible {
        /* Keep references to the filename and location so that
         * alternate persistence schemes have the option to archive
         * images symbolically rather than including the image data
         * in the archive.
         */Use ImageIO#read to return an Image and the constructor of ImageIcon that takes an Image as parameter and you'll be set.
    db
    edit Next itme, no help. I dislike cross posters.
    [http://forums.sun.com/thread.jspa?threadID=5340651]
    Edited by: Darryl.Burke

  • Images in jlabel -further query to peio1 and evert1234

    hi,
    I found a problem in bringing out images in jlabel.
    thanks for evert1234 for your reply.
    thanks for peio for your sample code.
    I found an error "cannot resolve symbol"
    for frame.getContentPane().I extended JFrame in the
    class I implemented this init() method.
    getContentPane is working correctly when called simply.
    Being a UG student undertaking a training in java
    swings I have a little maturity in java bugs.
    please guide me.
    yours friendly,
    mohan raj

    Hello ,
    try to no rewritte a new topic for a same problem. You have only to do a reply..
    For your problem try the further source.. I think it will help you
    // ImageLabelExample.java
    // Variations on a text & icon label.
    import javax.swing.*;
    import java.awt.*;
    public class ImageLabelExample {
    // put your address ICON
    private static Icon icon = new ImageIcon("images/smile.gif");
    public static void main(String[] args) {
    JLabel l;
    // create JLabel
         l=makeLabel(JLabel.TOP,JLabel.LEFT);
    // Add the labels to a frame and display it
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container c = frame.getContentPane();
    c.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 3));
    c.add(l);
    frame.setSize(350,150);
    frame.setVisible(true);
    protected static JLabel makeLabel(int vert, int horiz) {
    JLabel l = new JLabel("Smile", icon, SwingConstants.CENTER);
    l.setVerticalTextPosition(vert);
    l.setHorizontalTextPosition(horiz);
    l.setBorder(BorderFactory.createLineBorder(Color.black));
    return l;
    Do not forget to give the Duke Dollars ;)
    Thanks
    Best regards

  • 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

  • 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 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();
    }

  • Painting GIF images/using JLabels for GIFs... Somehow, make it work!

    Ok, I am basically making an arena for a local multiplayer game for my friends, and across the top of the screen is a title ... lets call the title "Game Title". The entire game is contained in 1 JFrame, including the title, sidebars, and the actual "game" part in the middle. I paint all of the objects in the game by painting them in the JFrame's Graphics when the paint() method is called.
    Basically, the window looks like this:
    | /\./\./\./\./\....Game Title..../\./\./\./\./\ |
    |...........______________..............|
    |...........|.--.game area.--..|..............|
    |...........|_____________|..............|
    Where the /\./\./\'s are animated flames. I have tried to just make them as ImageIcons in JLabels, but no matter what I paint() after the labels are added, the window looks like this:
    | /\./\./\./\./\ .......................... /\./\./\./\./\ |
    |.........................................................|
    |.........................................................|
    |.........................................................|
    Where the flames are animated, but the "background" is always gray. I then tried to paint them as Images (g.drawImage(new ImageIcon(url).getImage(),0,0,null), but that only leaves the first frame of the animated GIF (in other words, its not animated).
    What do I do? I have been reading around the forums, but I cannot find a case where somebody needed the GIF inside a Component that they used for painting...
    Thanks for any help that you give!

    If you're going to paint use a graphic component to do your painting in and don't add any components to it. The 'paint' method in JFrame is called by swing to draw the JFrame and its components. Using it to do custom painting is tricky. You'll need to call 'super.paint' to allow the container to paint its children. See the method detail in the JFrame api (link is in the Container section of the api). Also check the 'paintComponent' and 'paint' methods in the JComponent api method details section.
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class Painting extends JPanel
        BufferedImage image;
        public Painting(BufferedImage image)
            this.image = image;
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            g.drawImage(image, 125, 175, this);
        private JPanel getTitlePanel()
            JLabel title = new JLabel("Game Title", JLabel.CENTER);
            JLabel flame1 = new JLabel("flames");
            JLabel flame2 = new JLabel("flames");
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            panel.add(flame1, gbc);
            panel.add(title, gbc);
            panel.add(flame2, gbc);
            return panel;
        public static void main(String[] args) throws IOException
            String path = "images/Bird.gif";
            BufferedImage bi = ImageIO.read(Painting.class.getResource(path));
            Painting painting = new Painting(bi);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(painting.getTitlePanel(), "North");
            f.getContentPane().add(painting);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Help centering image on jlabel

    hi,
    is there any way to center an image on a jlabel, aside from doing it in the constructor. i want to allow the user at anytime to set text or an image on a jlabel, allowing them to change it anytime. i'm able to get the text set and then remove it and place an image there instead, but the the problem is i want the image to be centered on the jlabel. any ideas on how to do this?
    Thanks.

    You need to make a ImageIcon to put on the JLabel.
    JLabel label = new JLabel("Hello World");
    label.setIcon(new ImageIcon("image.jpg"));I'm not sure how to do that in JBuilder 5, unless you can code that.

  • Image inside jLabel

    Hi,
    iam using a jlabel with the image inside it using the code
    ImageIcon image = new ImageIcon(new URL(url));
    imgLabel = new JLabel();
    imgLabel.setIcon(image);
    it is working fine but i cannot apply dimension for jLabel
    jLabel.setSize(); is not working it is taking the image size as the label size ..
    how to create the label with needed size with the image inside it..

    Thank u for the reply....here is my requirment
    i need to create a list of images inside a tabbedpane......that images are of different dimensions but i need to make them viwed as thumbnails.
    for that i used a panel inside the tabbedpane and created label inside it ,
    for that label i had set icon(which is the image i need view)..but the problem is the label with images are not coming in same dimension since the original source images are of differend dimension.......is there any solution for my problem

  • Fit image to JLabel or JButton

    I have searched the topic and found some instances of the Image package being used to resize images.
    I have a DB of images (think photos) that I want to display based on user input. The display size will be the same but the actual picture dimensions stored in the DB won't necessarily be.
    My experience is that the amount of image displayed in the JLabel is entirely based on the size of the image itself (i.e. a small image is completely displayed while a large image is partially displayed.
    I wish to have the image fit to the JLabel (or JButton) dynamically.
    Is there an obvious method I am overlooking?
    TIA,
    Sil

    Here is the code for getting the image from the DB. As you can see it is a byte[].
    private static byte[] image = retrieveImage2;
    private static byte[] retrieveImage2() throws Exception
            String query = "SELECT GifBlob FROM Blobfile WHERE Name = ?";
            ResultSet rs = null;
            PreparedStatement pstmt = null;
            Blob blob = null;
            try
               pstmt = conn.prepareStatement(query);
               pstmt.setString(1,"7.jpg");
               rs = pstmt.executeQuery();
               rs.next();
               blob = rs.getBlob("GifBlob");
               byte[] gifBlob = blob.getBytes(1, (int) blob.length());
               return gifBlob;
            }I then call the method to place the image on the JLabel
    public void addImage(byte[] byteImage) {  
            javax.swing.Icon iconImage = new javax.swing.ImageIcon(byteImage);
            jLabel1.setIcon(iconImage);I don't see where I can set the size of an ImageIcon. Should I be using a different way of converting the image?
    Thanks again,
    Sil

  • Chaning images in JLabels

    I have been reading similar topics on these forums and I have tried the suggestions that have been posted. As the topic inicates I am having trouble changing the image of a JLabel.
    Image img = Toolkit.getDefaultToolkit().createImage((String)deck.removeFirst());
    jl[i][t].setIcon(new ImageIcon(img));
    or just
    jl[i][t].setIcon(new ImageIcon(deck.removeFirst()));
    deck is a linked list that holds file paths for my deck of cards.
    jl is an array of JLabels.
    Thank you in advance

    import java.awt.*;
    import javax.swing.*;
    public class Test2 extends JFrame {
      public Test2() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        content.add(new MyLabel(new ImageIcon("C:\\duke.gif").getImage()));
        setSize(300, 300);
        setVisible(true);
      public static void main(String args[]) { new Test2(); }
    class MyLabel extends JLabel {
      Image image;
      public MyLabel(Image image) { this.image = image; }
      public void paintComponent(Graphics g) {
        g.fillRect(0,0,getWidth(),getHeight());
        g.drawImage(image,0,0,getWidth(),getHeight(),this);
    }

  • 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!!

  • Adding images to jlabel

    newb question...
    i have an image i'd like to put on a jlabel. i think i know the code but where do i put the image so it can be retrieved...here is the part of the code i use to show image...
    ImageIcon icon = new ImageIcon("whatever.gif");
    JLabel jLabel1 = new JLabel(icon);
    when i run the app with the code like this the image doesnt show. the image is in a folder on my desktop now. do i need to move it somewhere else so that it can be retrieved or do i need to change the code to tell where the image is? thanks.

    Place the gif in your classpath and load it like this:
    URL url= YourClass.class.getClassLoader(
            ).getResource("whatever.gif"); // YourClass is the                                       class name
    if ( url != null ) {
        ImageIcon icon = new ImageIcon(url).getImage();
        JLabel jLabel1 = new JLabel(icon);
    }regds,
    CA

Maybe you are looking for

  • Transportation issue: Dimension table

    Hi While transporting an infocube i am getting following error( RC#8). Key field /BIC/EABC-KEY_ABC05 missing. Specify maintenance status 'read only'. View /BIC/VABCF could not be activated This infocube was added with a new character and assigned to

  • Daily average consumption...

    Hi, We need to calculate the daily average consumption during the creation of the billing document and bring it at the installation fact level and also use the same for some of the seasonal(Winter)  billing periods as a billable consumption instead o

  • Why my PDF form doesn't work?

    Hello! I am having issues with my Adobe Acrobat Pro 10.1.2 I created a nice form for my client with a submit buttom to send his clients by email so they could share their answers on the same PDF straight to his inbox, but its not really working!!! Af

  • Ukelele generated custom keyboard layouts not working in Lion?

    I asked this question in the stackexchange site a few days ago.  Nothing I've tried has worked so far, except for creating a new account.  Because a fresh account works, it's got to be something with my preferences, right? http://apple.stackexchange.

  • (PVID) inconsistency *PVID_Inc Issue

    Hello, Issue: Vlan 1 is in (PVID) inconsistency state on the Core switch for some access switches trunk ports. Native Vlan is 1 (same on all the switches) Find the output below:Core Switch (6513) SW-Core#sh spanning-tree inconsistentports Name Interf