ImageIcon on a JLabel

I have a JLabel, artworkImgLabel into which I want to place another JLabel with an Icon and then display it but only when the user clicks the button. The rest of the JFrame is already being displayed ie. setVisible() has been called. The code below is the listener code for the button and everything compiles and runs fine but the image is not shown. The URL is fine as it works in other situations. Any help would be very much appreciated...
Icon icon=null;
try {
     icon = new ImageIcon(new URL(***myurl***));
} catch (Exception ex) {
//error code here
JLabel label = new JLabel(icon);
this.artworkImgLabel.add(label).validate();

JLabel.setIcon([your icon]);Really quite simple.
Here's a quick little demo:
import javax.swing.*;
     public class Test extends JFrame {
          private ImageIcon ii;
          private JLabel lbl;
          private JButton btn;
          public Test() {
               ii = new ImageIcon("notes.gif"); /* change this to the URL of one of YOUR images! */
               lbl = new JLabel("When you click on the Button this will change to an Image");
               btn = new JButton("Click Me!");
               getContentPane().setLayout(new java.awt.FlowLayout());
               getContentPane().add(lbl);
               getContentPane().add(btn);
               pack();
               setTitle("Image Test");
               setLocationRelativeTo(null);
               setDefaultCloseOperation(EXIT_ON_CLOSE);
                    btn.addActionListener(new java.awt.event.ActionListener() {
                         public void actionPerformed(java.awt.event.ActionEvent evt) {
                              lbl.setText("");
                              lbl.setIcon(ii);
          public static void main(String[] argv) { new Test().setVisible(true); }
     }See if that doesn't do what you want it to ;-).

Similar Messages

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

  • Inserting an ImageIcon into a JLabel

    Hello.
    I'm trying to insert an ImageIcon into a JLabel
    component which includes text.
    I want this JLabel to be a cell in a JTable,
    so i'm trying to add the ImageIcon inside the method
    public Component getTableCellRendererComponent
    (JTable table, Object value, boolean isSelected,
    boolean hasFocus, int row, int column)
    of class
    public class ClientCellRenderer extends
    DefaultTableCellRenderer
    the code regarding the ImageIcon is:
    JLabel label = new JLabel((String)value, icon, CENTER);
    return label;
    this code resides inside getTableCellRendererComponent.
    for some reason i don't see the ImageIcon in the JTable,
    although i see the text (which is (String)value).
    i hope someone could help me.
    thanks,
    Topa.

    Assuming that your image icon is being loaded correctly, the following will solve your problem.
    Replace these lines:
    JLabel label = new JLabel((String)value, icon,
    CENTER);
    return label;with these:
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    setIcon(icon);
    return this;
    This works because DefaultTableCellRenderer extends JLabel, and returns itself as the renderer component.

  • ImageIcons in a JLabel get their top-most row of pixels cut off

    Hello. I've added a "Loading..." screen to my application that basically consists of a JWindow with a background image. However, I've noticed something odd when adding an ImageIcon to a JLabel. It seems that any image I add gets its top row of pixels cut off. The small program below illustrates this.
    import javax.swing.*;
    import java.awt.*;
    public class JLabelTest {
       static final String WINDOW_IMAGE = "my_image.jpg";
        * Create and display the loading screen
       private static void displayLoadingScreen()
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                JWindow winLoadingScreen = new JWindow();
                ImageIcon loadingImg = new ImageIcon(WINDOW_IMAGE);
                JLabel lblImage = new JLabel(loadingImg);
                winLoadingScreen.getContentPane().add(lblImage);
                winLoadingScreen.pack();
                System.out.println("label dimensions:      " + lblImage.getSize().width + " x " + lblImage.getSize().height);
                System.out.println("image icon dimensions: " + loadingImg.getIconWidth() + " x " + loadingImg.getIconHeight());
                winLoadingScreen.setLocation(100, 100);
                winLoadingScreen.setVisible(true);
        * Entry point
        * @param args
       public static void main(String[] args)
          SwingUtilities.invokeLater(new Runnable() {
             public void run()
                displayLoadingScreen();
    }(Obviously, replace my_image.jpg with something else if you'd like to run the code on your own machine.)
    When I run the program with, say, an 800 x 600 resolution image, the output I get is:
    label dimensions:      800 x 599
    image icon dimensions: 800 x 600As you can see, the image gets "shortened" by one pixel when added to the JLabel. If you look at the image that is displayed, you can see that it's the top row that gets cut off. I've tried changing the layout of the JWindow that the JLabel is being added to, but that didn't change anything. I've tried using a number of different images in varying formats, and the same thing happens to all of them.
    Any ideas? Thanks in advance.

    Have you tried to set label's preferredSize manually?
    What happens when you add empty border t the label with some insets?
    regards,
    Stas

  • Resizing an imageIcon of a jLabel on a jLayeredPane

    I have 2 questions, somewhat related:
    Question 1:
    I have a jLayeredPane with a number of jLabels of imageIcons.
    I need to resize the top imageIcon when I move a slider. To get the top component on the jLayeredPane, I use:
    Component topComponent = layeredPane.getComponent(0);However, I can't figure out how to get the image IN the jLabel IN the Component to set its size. Any ideas?
    Question 2:
    Also, it is easy to add items to a jLayeredPane. For example:
    layeredPane.add(myLabel);but how do I delete an item?

    Q1:
    Component topComponent = layeredPane.getComponent(0);
    JLabel l=(JLabel)topComponent ;
    Q2:
    layeredPane.remove(layeredPane.getIndexOf(myLabel));
    Regards,
    Stas

  • Re: Problems loading an ImageIcon into a JLabel in a JApplet

    This applet refuses to load images whose names it reads from a file in the makeList() method below. It will read the same image in if I hardcode in the file name
    Well, have you checked to see that what is being read is the same as what you were hardcoding?

    Assuming that your image icon is being loaded correctly, the following will solve your problem.
    Replace these lines:
    JLabel label = new JLabel((String)value, icon,
    CENTER);
    return label;with these:
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    setIcon(icon);
    return this;
    This works because DefaultTableCellRenderer extends JLabel, and returns itself as the renderer component.

  • Align ImageIcon on JLabel

    Hi,
    I use an ImageIcon on a JLabel, which is embedded in a ScrollPane, which is embedded in a SplitPane. When I now resize the window or the SplitPane-side, the image is always centered on JLabel. But I want it to be in the upper left corner, since I have to assure that the upper left corner of the image is at (0,0). Otherwise other painting would move relative to the image.
    I tried
    setHorizontalAlignment(SwingConstants.RIGHT);
    setVerticalAlignment(SwingConstants.TOP);
    on JLabel, but only the latter had the proper effect. The former seems to be ignored. Is this a bug? How to work around?
    I use jdk v1.3.1_01 on Linux.
    Thanks for any help.
    Greets
    Puce

    You should embed your JLabel in a container with a flow layout with a left alignment:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ImageScrollPane extends JFrame {
         ImageScrollPane() {
              super("");
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              setBounds(100,100,685,513);
              Container c = new Container();
              c.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));
              c.add(new JLabel(new ImageIcon("im.jpg")));
              JScrollPane scroller = new JScrollPane(c);
              getContentPane().add(scroller);
              pack();
              setVisible(true);
         public static void main(String[] args) {
              new ImageScrollPane();
    }I hope this helps,
    Denis

  • ImageIcon Array and a JLabel

    Hey,
    I have an ImageIcon arrary and JLabel called ImageLabel on which the ImageIcon is. Bascically I want it to do this: if the ImageIcon on the ImageLabel is a certain icon, say [0] and the click was < 200, then set the ImageIcon to [1] (in effect changing what image is shown on the ImageLabel). And vice versa, as demonstrated by the following code:
    if (x < 200) and (ImageIcon theIcon = [0]) // if the click is below 200 on the x axis and theIcon is [0]
              setImageLabel.setIcon(ImageIcon[1]);if (x > 200) and (ImageIcon theIcon = [1]) // if the click is above 200 on the x axis and theIcon is [1]
              imageLabel.setIcon(ImageIcon[2);
    However that code doesn't work. What code would work?

    Thank you for your reply. I tried using the code, however, I am unsure as to how to use a 2D array.
    I think it may help if I elaborate on what I need to do:
    I have 80 images, and would like each image to be assigned to a coordinate, such as 1,1 on a coordinate
    plane that is 16 wide by 23 high. My first idea would be that you will need (16 * 23) = 368 images, not 80.
    By having each image as an integer, I could then set it to load another image when clicked.
    For instance I want the program to load with the image set to 1,1 (this image
    would be "images/1-1.gif".)
    Now, since you are on 1,1 and click on a certain area of the image, it loads 2,1 (that co ordinate having the image "images/2-1.gif". If you click on a different part of the 1,1 image, it would load 3,1 ("images/3-1.gif). etc.
    Sorry to say it, but you're still unclear on your goal: will you be only displaying one image at a time ? Do you expect 1 image
    to represent each of the (16 * 23) coordinates ? Do you mean that the label will change location depending on the mouse clicks ?
    Whatever your objective is, I don't see what is incompatible with the code I suggested in my previous reply.

  • Image Loaded From Database not Visible in JLabel

    import java.sql.*;
    import javax.swing.*;
    import java.awt.*;
    public class consqlimage
         public consqlimage()
              try
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   Connection con = DriverManager.getConnection("jdbc:odbc:dsn","sa","manshu");
                   Statement stat = con.createStatement();
                   ResultSet rs = stat.executeQuery("Select pic from t_image");
                   byte b[];
                   b = new byte[1000];
                   while(rs.next())
                        b= rs.getBytes("pic");
                   for(int a=0;a!=b.length;a++)
                        System.out.println(b[a]);
                   JFrame f = new JFrame();
                   ImageIcon i1 = new ImageIcon(b+"jpeg");
                   JLabel l1=new JLabel("january",i1,SwingConstants.LEFT);
                   f.getContentPane().add(l1);
                   f.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
                   f.setSize(500,500);
                   f.setVisible(true);
                   con.close();
              catch(Exception e)
                   System.out.println(e);
         public static void main(String args[])
              new consqlimage();
    }

    Any reason why you are adding the "jpeg" to the end of the byte array?
    You should only have to pass the byte array to the ImageIcon constructor.

  • JLabel click event to change picture

    Hi All,
    I am new to GUI programming and need some help.
    I am trying to get a picture of a match to change to a different picture of a match when i click on it.
    Below is how I'm currently trying to do it.
    import javax.swing.UIManager;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Application2 {
      boolean packFrame = false;
      //Construct the application
      public Application2() {
        Frame2 frame = new Frame2();
        //Validate frames that have preset sizes
        //Pack frames that have useful preferred size info, e.g. from their layout
        if (packFrame) {
          frame.pack();
        else {
          frame.validate();
        //Center the window
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = frame.getSize();
        if (frameSize.height > screenSize.height) {
          frameSize.height = screenSize.height;
        if (frameSize.width > screenSize.width) {
          frameSize.width = screenSize.width;
        frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
        frame.setVisible(true);
      //Main method
      public static void main(String[] args) {
        try {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        catch(Exception e) {
          e.printStackTrace();
        new Application2();
    public class Frame2 extends JFrame {
      JPanel contentPane;
      BorderLayout borderLayout1 = new BorderLayout();
      JPanel jPanel1 = new JPanel();
      ImageIcon match = new ImageIcon("match.JPG");
      ImageIcon match2 = new ImageIcon("match2.JPG");
      JLabel jLabel1 = new JLabel(match);
      JLabel jLabel2 = new JLabel(match2);
      //Construct the frame
      public Frame2() {
        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      //Component initialization
      private void jbInit() throws Exception  {
        contentPane = (JPanel) this.getContentPane();
        contentPane.setLayout(borderLayout1);
        this.setSize(new Dimension(400, 300));
        this.setTitle("Frame Title");
        jLabel1.addMouseListener(new Frame2_jLabel1_mouseAdapter(this));
        contentPane.add(jPanel1, BorderLayout.CENTER);
        jPanel1.add(jLabel1, null);
       // jPanel1.add(jLabel2, null);
      //Overridden so we can exit when window is closed
      protected void processWindowEvent(WindowEvent e) {
        super.processWindowEvent(e);
        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
          System.exit(0);
      void jLabel1_mouseClicked(MouseEvent e) {
        // DOESN'T seam to work
        jLabel1 = new JLabel(match2);
       // jPanel1.remove(jLabel1);
       // jPanel1.add(jLabel1);
        jPanel1.repaint();
        repaint();
    class Frame2_jLabel1_mouseAdapter extends java.awt.event.MouseAdapter {
      Frame2 adaptee;
      Frame2_jLabel1_mouseAdapter(Frame2 adaptee) {
        this.adaptee = adaptee;
      public void mouseClicked(MouseEvent e) {
        adaptee.jLabel1_mouseClicked(e);
    }

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Frame2Rx extends JFrame {
        JPanel contentPane;
        BorderLayout borderLayout1 = new BorderLayout();
        JPanel jPanel1 = new JPanel();
        ImageIcon match = new ImageIcon("images/bclynx.jpg");
        ImageIcon match2 = new ImageIcon("images/greathornedowl.jpg");
        ImageIcon[] icons;
        int iconCount;
        JLabel jLabel1 = new JLabel(match);
        JLabel jLabel2 = new JLabel(match2);
        //Construct the frame
        public Frame2Rx() {
            icons = new ImageIcon[] { match, match2 };
            iconCount = 0;
            enableEvents(AWTEvent.WINDOW_EVENT_MASK);
            try {
                jbInit();
            catch(Exception e) {
                e.printStackTrace();
        //Component initialization
        private void jbInit() throws Exception {
            contentPane = (JPanel) this.getContentPane();
            contentPane.setLayout(borderLayout1);
            this.setSize(new Dimension(400, 300));
            this.setTitle("Frame Title");
            jLabel1.addMouseListener(new Frame2_jLabel1_mouseAdapter(this));
            contentPane.add(jPanel1, BorderLayout.CENTER);
            jPanel1.add(jLabel1, null);
            // jPanel1.add(jLabel2, null);
        //Overridden so we can exit when window is closed
        protected void processWindowEvent(WindowEvent e) {
            super.processWindowEvent(e);
            if (e.getID() == WindowEvent.WINDOW_CLOSING) {
                System.exit(0);
        void jLabel1_mouseClicked(MouseEvent e) {
            jLabel1.setIcon(icons[++iconCount % icons.length]);
            jLabel1.revalidate();  // esp if image sizes not equal
            jLabel1.repaint();
        public static void main(String[] args)
            Frame2Rx f = new Frame2Rx();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setVisible(true);
    class Frame2_jLabel1_mouseAdapter extends java.awt.event.MouseAdapter {
        Frame2Rx adaptee;
        Frame2_jLabel1_mouseAdapter(Frame2Rx adaptee) {
            this.adaptee = adaptee;
        public void mouseClicked(MouseEvent e) {
            adaptee.jLabel1_mouseClicked(e);
    }

  • Change of  image in JLabel doesn't appear

    Hi!
    In my custom JPanel class, I add a JLabel with nothing in it. Then. When auser clicks a Button, I set an imageicon for this jlabel. but it doesn't appear until I force a repaint, e.g. by resizing the app.
    repaint(), validate() or invalidate() didn't work!
    thank you!

    thank you, problem found! t'was not caused bei repaint ;)

  • Using ImageIcon in Linux

    Hi,
    I tried to use jpg image inside JLabel. This is working in Windows. But I tried in RedHat Linux 9. I can't see the jpg image inside the label. I have included the code.
    Thanks in advance.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    class jpgTest extends JFrame
         public jpgTest()
              super("jpg image test");
              Container cpane=getContentPane();
              cpane.setLayout(new FlowLayout());
              File jpgFile=new File(System.getProperty("user.dir"),"folder.jpg");
              JLabel lblImage=new JLabel("folder.jpg",new ImageIcon(jpgFile.getAbsolutePath()),JLabel.CENTER);
              lblImage.setVerticalTextPosition(JLabel.BOTTOM);
              lblImage.setHorizontalTextPosition(JLabel.CENTER);
              cpane.add(lblImage);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              Toolkit t=Toolkit.getDefaultToolkit();
              Dimension d=t.getScreenSize();
              setSize(d.width,d.height-30);
              setVisible(true);
              setExtendedState(JFrame.MAXIMIZED_BOTH);
         public static void main(String args[])
              new jpgTest();
    }

    Your code worked fine for me. Maybe your image got messed up when you copied it from Windows to Linux (if you use FTP without setting binary mode, that will happen).
    Can you see the JPEG with your browser?

  • Custom Icon in JLabel - center?

    I have a custom Icon that I am placing in a JLabel, but I can't get it to be centered!
    I can put an ImageIcon in the JLabel, and it will be centered, but my custom Icon doesn't seem to follow the setVerticalAlignment/setHorizontalAlignment properties.
    I am using java 1.3.1.
    Any suggestions?

    The first thing I would do is check the frame of the custom icon to see if it is bigger than the picture...that could be the problem.

  • Problem with two JLabels on panel on mouseover

    Hello all,
    I have created a JPanel and I have placed two JLabels on it. I have assigned an icon to each of them. What I want to do is to change this icons to different ones (a "highlighted" version of them) for each one of my JLabels when the mouse is over them. My problem is that with the code i have right now, both change when I mouse over only the first one while nothing happens when i do the same for the 2nd one. As a second step I want to move this two labels along the y-axis. Again only jLabel1 can be moved and only for a few points (that seem to be on the bounds of its original bounds) and jLabel2 gets the exact same movement even though I'm not dragging over it. I hope it's clear what I want to do. So my question is: i) why both my jLabels get highlighted when I mouse over the one and ii) why i can move my jLabel only to a restricted area in the screen? (actually I know the reason for this but I still cannot understand why it's happening: when I drag my image, it doesn't update its location. So if I mouse over its initial location it gets highlighted which means that it thinks it's still there for some reason, although it's repainted in its new position..)
    package Viewer;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    * @author  Laura
    public class Test2 extends javax.swing.JPanel {
        BufferedImage  img1=null;
        BufferedImage  img2=null;
        BufferedImage  img3=null;
        BufferedImage  img4=null;
        ImageIcon icon1=null;
        ImageIcon icon2=null;
        ImageIcon icon1_h=null;
        ImageIcon icon2_h=null;
        JLabel jLabel1;
        JLabel jLabel2;
        public Test2 (ColoringProperties parent) {
            try {
                img1=ImageIO.read((getClass().getResource("/arrow_right.gif")));
                icon1=new ImageIcon(img1);
                img2=ImageIO.read((getClass().getResource("/arrow_left.gif")));
                icon2=new ImageIcon(img2);
                img3=ImageIO.read((getClass().getResource("/arrow_right_highlighted.gif")));
                icon1_h=new ImageIcon(img3);
                img4=ImageIO.read((getClass().getResource("/arrow_left_highlighted.gif")));
                icon2_h=new ImageIcon(img4);
            } catch (IOException exc) {
            initComponents();
            jLabel1=new JLabel(icon1);
            jLabel2=new JLabel(icon2);
            this.add(jLabel1);
            this.add(jLabel2);
        public void PlaceIcons(){
            Dimension size = this.getSize();
            if (icon1 != null) {
                jLabel1.setBounds(0, 0,icon1.getIconWidth(),icon1.getIconHeight());
                jLabel1.setOpaque(true);
            } else {
                System.err.println("icon not found; using black square instead.");
                jLabel1.setBounds(0, 0, 30, 30);
                jLabel1.setOpaque(true);
                jLabel1.setBackground(Color.BLACK);
            if (icon2 != null) {
                jLabel2.setBounds(size.width - icon2.getIconWidth(), size.height - icon2.getIconHeight(),
                        icon2.getIconWidth(),icon2.getIconHeight());  
                jLabel2.setOpaque(true);
            } else {
                System.err.println("icon not found; using black square instead.");
                jLabel2.setBounds(0, 0, 30, 30);
                jLabel2.setOpaque(true);
                jLabel2.setBackground(Color.BLACK);
        private void initComponents() {
            addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    formMouseEntered(evt);
                public void mouseExited(java.awt.event.MouseEvent evt) {
                    formMouseExited(evt);
            addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
                public void mouseDragged(java.awt.event.MouseEvent evt) {
                    formMouseDragged(evt);
                public void mouseMoved(java.awt.event.MouseEvent evt) {
                    formMouseMoved(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 54, Short.MAX_VALUE)
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 323, Short.MAX_VALUE)
        private void formMouseExited(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
            this.jLabel1.setIcon(this.icon1);
            this.jLabel2.setIcon(this.icon2);
            this.repaint();
        private void formMouseMoved(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
            Point p=new Point(evt.getPoint());
            if (this.jLabel1.contains(p)){
                this.jLabel1.setIcon(this.icon1_h);
                this.repaint();
            else {
                this.jLabel1.setIcon(this.icon1);
                this.repaint();
            if (this.jLabel2.contains(p)){
                this.jLabel2.setIcon(this.icon2_h);
                this.repaint();
            else{
                this.jLabel2.setIcon(this.icon2);
                this.repaint();
        private void formMouseDragged(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
            Point p=new Point(evt.getPoint());
            if (this.jLabel1.contains(p)){
                Point init=this.jLabel1.getLocation();
                this.jLabel1.setLocation(init.x,p.y);
                this.repaint();
            if (this.jLabel2.contains(p)){
                Point init=this.jLabel2.getLocation();
                this.jLabel2.setLocation(init.x,p.y);
                this.repaint();
    }Any help would be appreciated. I'm not an experienced programmer and I'm using NetBeans IDE 6.0.1 (if that's of any help)
    Thank you,
    Laura

    Thanx for the replies!
    I did what Rodney suggested and indeed the Labels now move independently. However, there is a lot of flickering and a ghost label appears that moves respectively with the original one i'm dragging (for both of them). Any ideas why is that?
    Thank you again,
    Laura
    package Viewer;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    * @author  Laura
    public class Test2 extends javax.swing.JPanel {
        BufferedImage  img1=null;
        BufferedImage  img2=null;
        BufferedImage  img3=null;
        BufferedImage  img4=null;
        ImageIcon icon1=null;
        ImageIcon icon2=null;
        ImageIcon icon1_h=null;
        ImageIcon icon2_h=null;
        public Test2(ColoringProperties parent) {
            try {
                img1=ImageIO.read((getClass().getResource("/arrow_right.gif")));
                icon1=new ImageIcon(img1);
                img2=ImageIO.read((getClass().getResource("/arrow_left.gif")));
                icon2=new ImageIcon(img2);
                img3=ImageIO.read((getClass().getResource("/arrow_right_highlighted.gif")));
                icon1_h=new ImageIcon(img3);
                img4=ImageIO.read((getClass().getResource("/arrow_left_highlighted.gif")));
                icon2_h=new ImageIcon(img4);
            } catch (IOException exc) {
            initComponents();       
        public void PlaceArrows(){
            Dimension size = this.getSize();
            if (icon1 != null) {
                jLabel1.setBounds(0, 0,icon1.getIconWidth(),icon1.getIconHeight());
                jLabel1.setOpaque(true);
            } else {
                System.err.println("icon not found; using black square instead.");
                jLabel1.setBounds(0, 0, 30, 30);
                jLabel1.setOpaque(true);
                jLabel1.setBackground(Color.BLACK);
            if (icon2 != null) {
                jLabel2.setBounds(size.width - icon2.getIconWidth(), size.height - icon2.getIconHeight(),
                        icon2.getIconWidth(),icon2.getIconHeight());  
                jLabel2.setOpaque(true);
            } else {
                System.err.println("icon not found; using black square instead.");
                jLabel2.setBounds(0, 0, 30, 30);
                jLabel2.setOpaque(true);
                jLabel2.setBackground(Color.BLACK);
        private void initComponents() {
            jLabel1 = new JLabel(icon1);
            jLabel2 = new JLabel(icon2);
            addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    formMouseEntered(evt);
                public void mouseExited(java.awt.event.MouseEvent evt) {
                    formMouseExited(evt);
            addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
                public void mouseDragged(java.awt.event.MouseEvent evt) {
                    formMouseDragged(evt);
                public void mouseMoved(java.awt.event.MouseEvent evt) {
                    formMouseMoved(evt);
            jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    jLabel1MouseEntered(evt);
                public void mouseExited(java.awt.event.MouseEvent evt) {
                    jLabel1MouseExited(evt);
            jLabel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
                public void mouseDragged(java.awt.event.MouseEvent evt) {
                    jLabel1MouseDragged(evt);
            jLabel2.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    jLabel2MouseEntered(evt);
                public void mouseExited(java.awt.event.MouseEvent evt) {
                    jLabel2MouseExited(evt);
            jLabel2.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
                public void mouseDragged(java.awt.event.MouseEvent evt) {
                    jLabel2MouseDragged(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(41, Short.MAX_VALUE))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(42, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 295, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
        private void formMouseEntered(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:       
        private void formMouseExited(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
        private void formMouseMoved(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
        private void formMouseDragged(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
        private void jLabel1MouseEntered(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
            this.jLabel1.setIcon(this.icon1_h);
            this.jLabel1.revalidate();
            this.repaint();
        private void jLabel1MouseExited(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
            this.jLabel1.setIcon(this.icon1);
            this.jLabel1.revalidate();
            this.repaint();
        private void jLabel1MouseDragged(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
            Point w=new Point(evt.getPoint());
            if (w.y>0 && w.y<this.getHeight()){
                Point init=this.jLabel1.getLocation();
                this.jLabel1.setIcon(this.icon1_h);
                this.jLabel1.setLocation(init.x,w.y);
                this.jLabel1.revalidate();
                this.jLabel1.repaint();
        private void jLabel2MouseEntered(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
            this.jLabel2.setIcon(this.icon2_h);
        private void jLabel2MouseExited(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
            this.jLabel2.setIcon(this.icon2);
        private void jLabel2MouseDragged(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
            Point p=new Point(evt.getPoint());
            if (p.y>0 && p.y<this.getHeight()){
                Point init=this.jLabel2.getLocation();
                this.jLabel2.setIcon(this.icon2_h);
                this.jLabel2.setLocation((int)init.getX(),(int)p.getY());
        // Variables declaration - do not modify
        public javax.swing.JLabel jLabel1;
        public javax.swing.JLabel jLabel2;
        // End of variables declaration
    }

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

Maybe you are looking for

  • Open .xlf file created in 5.0 in version 4.5

    Is there a way to save an Xcelsius file in version 5.0 (Engage) and open it in version 4.5?

  • Help on Multiselect list

    I created a Multiselect list for item :P5_REGIONS(USING DYNAMIC ) DYNAMIC QUERY IS SELECT DISTINCT DEPTNO FROM DEPT; Mutiselect list 10 20 30 40 50 I have another item name :P5_SELECTED_REGIONS So what I want to do is When user select multi values fr

  • Jnlp interpreted by the client or the webserver ?

    Hello there, I just want to clear this up - Is the .jnlp file sent to the client (where web start will inspect it) or by the webserver ? So, when the jnlp file is made to point to a particular applet etc., will the webserver look at the jnlp and forw

  • Require Education ID for upgrade?

    Hi, I am currently a staff member at a university and therefore am elegible to purchase a student/teacher edition of CS5 Master Collection. However, I want to be sure that when the next upgrade comes along, if I am not employed by an educational inst

  • Help me! don't know the password

    i got my macbook air as a gift and the guy on the store put a name and password for me, how can i change it???? i even don't know the password!!!