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

Similar Messages

  • Having some problems with ImageIcons and JLabels

    I'm making a checkers game, and so far it's going pretty well.
    I've got the basic game down, and you can move pieces, jump, your turn ends when you can't jump anymore, etc...
    However, I've had three problems:
    1.) I'm using JLabels to display my board (8 x 8.. well actually 9 x 9 for an outer row labelled A,B,C,D.. 1,2,3,4...) Anyway, I create the JLabels using something that looks like \:
    JLabel square = new JLabel(new ImageIcon("pic.png"));
    Now, the picture loads properly, but it seems like the picture is being cropped, and the top and bottom are getting chopped off, so my 36 x 36 pixel *.gif appears to be 36 x 30.
    You can see how there is a gap created in:
    http://img235.imageshack.us/img235/7765/prob13ky.jpg
    Now the problem may be with the GridLayout I am using, but I set the distance between the components in the container to be 0, 0 so I don't think that GridLayout is chopping my icons. I've also tried setPreferredSize(new Dimension(36,36))
    for both my ImageIcons and JLabels and for my container (which I set to size 2000,2000, just to make sure there was room). If anyone can help me, it's be appreciated.
    2.) I used to be able to view my outside row/column of squares that said A,B,C,D.... and 1,2,3,4... with the square in the corner having a random pic. For some reason now (have no clue why) I now see only the pic in the corner, and then a little gray smudge diagonally under it.
    Pic:
    http://img347.imageshack.us/img347/8308/prob24im.jpg
    I don't know what's wrong. I'm pretty sure it's none of the new methods I've written, as those are all in my static void main (String[] ar) ...... and if I comment all the methods in my main except where I first make the JFrame and set it visible, it still turns out like that. repaint() doesn't help.
    3.) For some reason, when I move another window (AIM, the console window, etc...) over my Swing window, it "erases" (turns gray, just wipes clean) the part where I have my squares that have pieces.
    What's weird is that:
    The border pieces (err.. my one visible corner piece from my second problem) don't get wiped, and some debugging text and JLabels (in a different JPanel) are fine. I don't think the JPanel matters though; the border pieces and the playing squares (which get wiped) are in the same JPanel and same array of squares.
    repaint(); also erases ALL of my playing squares, whereas moving a window over them would only erase the part that the window covered.
    Also, I added a mouseListener so that whenever I move the mouse over a square, it changes the image (to a tinted version, so you know the mouse is over it) and when you move the mouse away, it returns to normal. However, if I wildly swing the mouse around the area, it seems to lock up and freeze for a few seconds. Is there anything I can do to prevent this??
    Thanks in advance.

    It is hard to tell what your problems are without any code at all (I saw your images, but that doesn't make it easy to see what is wrong in your code). If you do post code, please use code tags (see button above posting box).
    I've seen your MouseListener problem before--we had the exact same issue in our code at work. It would freeze up while it processed all of the mouse events (unbearably slow). I'm not at work right now, so I don't recall how it was fixed. Essentially, you need to only process the event periodically. You need to only update the image if the mouse switches squares. Or, only update the image if the distance from the last mouse event is more than some specified amount. We might also have checked the time difference between mouse events before processing a new one. I could look at the code at work tomorrow, if you are still having trouble.

  • Aligning text in JLabel

    Hi all,
    I'm simply trying to align text in a JLabel.
    I've been trying to use HTML formatting inside the JLabel, e.g:
    label = new JLabel (" <HTML><CENTER><P>Line one</P> <P>Line two</P></CENTER> </HTML>" );but when I try to use the <CENTER> tag it seems to be ignored?
    Why?
    How do I get around this?
    Many thanks.

    You can use the following code segment:
    JLabel ab = new JLabel("GG" ,  SwingConstants.CENTER);Hope it helps.
    --DM                                                                                                                                                                                                                                                                       

  • Unable to set imageicon to JLabel

    hi
    I have base64 encoded image data, i am decoding this and trying to create an image icon object by passing decoded byte array.
    I am using apaches codec commons for base64 encoding and decoding.
    i have base64 converted tried with this code, but failing to display
    public class Display extends JFrame {
         public Display(String theImageData) {
              byte[] byteimage = Base64.decodeBase64(theImageData.getBytes());
              JLabel image = new JLabel();     
              getContentPane().setLayout(new BorderLayout());
              ImageIcon icon = new ImageIcon(byteimage);
              image.setIcon(icon);
              getContentPane().add(image, Borderlayout.CENTER);
    }when the window is displayed, the label doesn't display the image on it.
    thanks

    First, have you written code that verifies that when you encode and then decode the image data, the result is a byte-by-byte equivalent byte[]?
    Second, have you checked to see what your ImageIcon can tell you about it's image loading:
    int status = icon.getImageLoadStatus();

  • Scale/Stretch ImageIcon to JLabel

    I was wondering if there was any way to stretch an ImageIcon to fit the containing JLabel.

    Pleace could you paste the resulting code? u see, I`m having a similar problem, I tried to use this code but I get an error, I dont know which varriable should i use :
    myImageIcon.getImage() <==== cant find symbol
    JPfoto.add(new JLabel(new ImageIcon("/root/Desktop/UTN/Cliente/pesado/NetBeans_Projects/Tenasiuspesado1/java_logo.gif"))               {
                           @Override
                           public void paintComponent (Graphics g) {
                              super.paintComponent (g);
                              g.drawImage (myImageIcon.getImage(), 0, 0, getWidth (), getHeight (), null);
                        });

  • Problem setting ImageIcon onto JLabel

    Hi guys I am currently writing a Pente board game.
    Now I have two classes called Stone and GameStatus.
    In the GameStatus constructor it basically generates a JPanel and I try to fill it with 19 x 19 JLabel and add a mouselistener to each of them. This way when the label gets clicked, I can change the Image of it to represents empty spot, with white stone or with black stone.
    Here is the code of Stone class
    package pente;
    import javax.swing.*;
    public class Stone extends JLabel
      // the color of the Stone object
      private String color;
      private int x, y; // the location of current Stone
      boolean occupied; // see if the spot is occupied
      // the location of each image file
      private final String EMPTY = "c:/empty.jpg";
      private final String BLACK = "c:/black.jpg";
      private final String WHITE = "c:/white.jpg";
      // private JLabel label = new JLabel();
      * The default constructor that initializes a
      * Stone object with a given color.
      public Stone(int x, int y, boolean o, String c)
          this.x = x;
          this.y = y;
          this.occupied = o;
          this.color = "empty"; // the color has not yet been set
          this.setIcon(new ImageIcon(EMPTY));
        // assign the given color to the Stone
       * This method sets the image of the current object depends on
       * the given variable c.
       * @return the Stone object with an appropriate image on it
      public Stone setColor(String c)
          // swtich the image of the Panel depends on the c given
          if ((c.equals("w")) || (c.equals("white")))
            this.color = "white";
            this.setIcon(new ImageIcon(WHITE));
          else if ((c.equals("b")) || (c.equals("black")))
              this.color = "black";
              this.setIcon(new ImageIcon(BLACK));
          return this;
       * This method replaces the current image with the empty image
       * @return the Stone object with empty image on it
      public Stone setEmpty()
          this.color = "empty";
          this.setIcon(new ImageIcon(EMPTY));
          return this;
       * This method gets the x coordinate of Stone
       * @return the x coordinate
      public int getX()
          return this.x;
       * This method gets the y coordinate of Stone
       * @return the y coordinate
      public int getY()
          return this.y;
       * This method tests if the current Stone has been set to a color
       * @return if the Stone has been set to a color
      public boolean isOccupied()
          return (!(this.color).equals("empty"));
    }Here is the part where GameStatus calls Stone class
    public GameStatus(int size)
            this.setTitle("PENTE");
            this.setLocation(100,30);
            this.setSize(747,695);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel p = new JPanel();
            p.setLayout(new GridLayout(0, size, 0, 0));
            // initializes the array and starts inserting labels
            for (int i = 0; i < size ; i++)
                for (int j = 0; j < size ; j++)
                    array[i][j] = new infoArray(i, j, false, EMPTY);
                    Stone s = new Stone(i, j, false, EMPTY);
                    s.addMouseListener(new MousePressListener());
                    p.add(s);
            this.setResizable(false);
            this.getContentPane().add(p);
            this.setVisible(true);
            System.out.print("hello");
        }The problem is, there is only one Stone object can be shown on the JPanel.
    This is weird since it works fine when I tried to call JLabel object instead of Stone object and fill them into JPanel.
    Since Stone class extends JLabel, I just dont see why JLabel works while Stone doesn't.
    I need to know the reason badly, so I appreciate any suggestions.
    Thanks.

    Code looks reasonable. Only comment I have is that icons can be shared by multiple components. So you only need to create 3 icons, one for each state of the stone. Then you just use setIcon to change the state. No need to recreate the icon every time.

  • Set Horizontal Alignment on JLabel - wrong implementation?

    Hi again.
    I am studying by myself, and my last resort is to show you my unfinished code. This is supposed to move the alignment of the JLabel at the top of the window depending on the ComboBox choice. I did not implement the other ItemListeners yet because I can't make the first one work. I know I have an error somewhere... anyway thanks in advance for your time.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class DemoJLabel extends JFrame {
        private ImageIcon icon = new ImageIcon("image/grapes.gif");
        private JLabel jlblGrape = new JLabel("Grapes", icon, SwingConstants.CENTER);
        private String[] horizontalAlign = {"LEFT", "CENTER", "RIGHT",
            "LEADING", "TRAILING"
        private String[] verticalAlign = {"TOP", "CENTER", "BOTTOM"};
        private String[] horizontalTP = {"LEFT", "CENTER", "RIGHT", "LEADING",
            "TRAILING"
        private String[] verticalTP = {"TOP", "CENTER", "BOTTOM"};
        private JComboBox jcboHA = new JComboBox(horizontalAlign);
        private JComboBox jcboVA = new JComboBox(verticalAlign);
        private JComboBox jcboHT = new JComboBox(horizontalTP);
        private JComboBox jcboVT = new JComboBox(verticalTP);
        public DemoJLabel() {
            JPanel p1 = new JPanel();
            p1.setLayout(new FlowLayout());
            p1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            p1.add(jlblGrape);
            JPanel p2 = new JPanel();
            p2.setLayout(new GridLayout(2, 1));
            p2.add(new JLabel("Horizontal"));
            p2.add(new JLabel("Vertical"));
            JPanel p3 = new JPanel();
            p3.setLayout(new GridLayout(2, 1));
            p3.add(jcboHA);
            p3.add(jcboVA);
            JPanel p4 = new JPanel();
            p4.setLayout(new BorderLayout());
            p4.setBorder(BorderFactory.createTitledBorder("Alignment"));
            p4.add(p2, BorderLayout.WEST);
            p4.add(p3, BorderLayout.EAST);
            JPanel p5 = new JPanel();
            p5.setLayout(new GridLayout(2, 1));
            p5.add(new JLabel("Horizontal"));
            p5.add(new JLabel("Vertical"));
            JPanel p6 = new JPanel();
            p6.setLayout(new GridLayout(2, 1));
            p6.add(jcboHT);
            p6.add(jcboVT);
            JPanel p7 = new JPanel();
            p7.setLayout(new BorderLayout());
            p7.setBorder(BorderFactory.createTitledBorder("Text Position"));
            p7.add(p5, BorderLayout.WEST);
            p7.add(p6, BorderLayout.EAST);
            JPanel p8 = new JPanel();
            p8.setLayout(new GridLayout());
            p8.add(p4);
            p8.add(p7);
            setLayout(new GridLayout(2, 1));
            add(p1);
            add(p8);
            jcboHA.addItemListener(new ItemListener() {
                public void itemStateChanged(ItemEvent e) {
                    //For debugging
                    System.out.println(jcboHA.getSelectedItem());
                    String choice = jcboHA.getSelectedItem().toString();
                    if (choice.equals("LEFT")) {
                        jlblGrape.setHorizontalAlignment(JLabel.LEFT);
                    } else if (choice.equals("CENTER")) {
                        jlblGrape.setHorizontalAlignment(JLabel.CENTER);
                    } else if (choice.equals("RIGHT")) {
                        jlblGrape.setHorizontalAlignment(JLabel.RIGHT);
                    } else if (choice.equals("LEADING")) {
                        jlblGrape.setHorizontalAlignment(JLabel.LEADING);
                    } else {
                        jlblGrape.setHorizontalAlignment(JLabel.TRAILING);
        // Other ItemListeners for the other combo boxes
        public static void main(String[] args) {
            DemoJLabel frame = new DemoJLabel();
            frame.setTitle("Demonstrating JLabel");
            frame.setSize(400, 350);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
    }

    *@petes1234*
    Thanks! I didn't think about declaring p1 so that it could be changed.
    * with assistance from petes1234
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class DemoJLabel extends JFrame
        //** make the label's panel visible to the whole class
        private JPanel p1;
        private ImageIcon icon = new ImageIcon("image/grapes.gif");
        private JLabel jlblGrape = new JLabel("Grapes", icon, SwingConstants.CENTER);
        private String[] horizontalAlign =
        { "LEFT", "CENTER", "RIGHT", "LEADING", "TRAILING" };
        private String[] verticalAlign =
        { "TOP", "CENTER", "BOTTOM" };
        private String[] horizontalTP =
        { "LEFT", "CENTER", "RIGHT", "LEADING", "TRAILING" };
        private String[] verticalTP =
        { "TOP", "CENTER", "BOTTOM" };
        private JComboBox jcboHA = new JComboBox(horizontalAlign);
        private JComboBox jcboVA = new JComboBox(verticalAlign);
        private JComboBox jcboHT = new JComboBox(horizontalTP);
        private JComboBox jcboVT = new JComboBox(verticalTP);
        public DemoJLabel()
            //** make label bigger so we can see it
            //** the text moving around inside of it
            int labelSize = 160;
            jlblGrape.setPreferredSize(new Dimension(2 * labelSize, labelSize - 15));
            //** give it a border so we can see its bounds
            jlblGrape.setBorder(BorderFactory.createLineBorder(Color.blue));
            p1 = new JPanel();
            p1.setLayout(new FlowLayout());
            p1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            p1.add(jlblGrape);
            JPanel p2 = new JPanel();
            p2.setLayout(new GridLayout(2, 1));
            p2.add(new JLabel("Horizontal"));
            p2.add(new JLabel("Vertical"));
            JPanel p3 = new JPanel();
            p3.setLayout(new GridLayout(2, 1));
            p3.add(jcboHA);
            p3.add(jcboVA);
            JPanel p4 = new JPanel();
            p4.setLayout(new BorderLayout());
            p4.setBorder(BorderFactory.createTitledBorder("Alignment"));
            p4.add(p2, BorderLayout.WEST);
            p4.add(p3, BorderLayout.EAST);
            JPanel p5 = new JPanel();
            p5.setLayout(new GridLayout(2, 1));
            p5.add(new JLabel("Horizontal"));
            p5.add(new JLabel("Vertical"));
            JPanel p6 = new JPanel();
            p6.setLayout(new GridLayout(2, 1));
            p6.add(jcboHT);
            p6.add(jcboVT);
            JPanel p7 = new JPanel();
            p7.setLayout(new BorderLayout());
            p7.setBorder(BorderFactory.createTitledBorder("Text Position"));
            p7.add(p5, BorderLayout.WEST);
            p7.add(p6, BorderLayout.EAST);
            JPanel p8 = new JPanel();
            p8.setLayout(new GridLayout());
            p8.add(p4);
            p8.add(p7);
            setLayout(new GridLayout(2, 1));
            add(p1);
            add(p8);
            jcboHA.addItemListener(new ItemListener()
                public void itemStateChanged(ItemEvent e)
                    String choice = jcboHA.getSelectedItem().toString();
                    if (choice.equals("LEFT"))
                        jlblGrape.setHorizontalAlignment(JLabel.LEFT);
                    else if (choice.equals("CENTER"))
                        jlblGrape.setHorizontalAlignment(JLabel.CENTER);
                    else if (choice.equals("RIGHT"))
                        jlblGrape.setHorizontalAlignment(JLabel.RIGHT);
                    else if (choice.equals("LEADING"))
                        jlblGrape.setHorizontalAlignment(JLabel.LEADING);
                    else
                        jlblGrape.setHorizontalAlignment(JLabel.TRAILING);
                    //** revalidate the panel after making changes
                    p1.revalidate();
            jcboVA.addItemListener(new ItemListener()
                public void itemStateChanged(ItemEvent e)
                    String choice = jcboVA.getSelectedItem().toString();
                    if (choice.equals("TOP"))
                        jlblGrape.setVerticalAlignment(JLabel.TOP);
                    else if (choice.equals("CENTER"))
                        jlblGrape.setVerticalAlignment(JLabel.CENTER);
                    else
                        jlblGrape.setVerticalAlignment(JLabel.BOTTOM);
                    //** revalidate the panel after making changes
                    p1.revalidate();
            jcboHT.addItemListener(new ItemListener()
                public void itemStateChanged(ItemEvent e)
                    String choice = jcboHT.getSelectedItem().toString();
                    if (choice.equals("LEFT"))
                        jlblGrape.setHorizontalTextPosition(JLabel.LEFT);
                    else if (choice.equals("CENTER"))
                        jlblGrape.setHorizontalTextPosition(JLabel.CENTER);
                    else if (choice.equals("RIGHT"))
                        jlblGrape.setHorizontalTextPosition(JLabel.RIGHT);
                    else if (choice.equals("LEADING"))
                        jlblGrape.setHorizontalTextPosition(JLabel.LEADING);
                    else
                        jlblGrape.setHorizontalTextPosition(JLabel.TRAILING);
                    //** revalidate the panel after making changes
                    p1.revalidate();
             jcboVT.addItemListener(new ItemListener()
                public void itemStateChanged(ItemEvent e)
                    String choice = jcboVT.getSelectedItem().toString();
                    if (choice.equals("TOP"))
                        jlblGrape.setVerticalTextPosition(JLabel.TOP);
                    else if (choice.equals("CENTER"))
                        jlblGrape.setVerticalTextPosition(JLabel.CENTER);
                    else
                        jlblGrape.setVerticalTextPosition(JLabel.BOTTOM);
                    //** revalidate the panel after making changes
                    p1.revalidate();
        public static void main(String[] args)
            DemoJLabel frame = new DemoJLabel();
            frame.setTitle("Demonstrating JLabel");
            frame.setSize(400, 350);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
    }Edited by: carlshark on Dec 18, 2007 4:30 AM
    Removed unnecessary debugging code

  • 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

  • Which is better for drawing JPGs on JLabel: ImageIcon or directly?

    I'm currently using this everywhere.
    BufferedImage bi;
    Jlabel jLabel;
    ImageIcon img = new ImageIcon( bi );
    jLabel.setIcon(imgIcon);but now I've discovered I can write images directly to the component from paintComponent( Graphics g )
    (from a subclass of JLabel)
    public void paintComponent( Graphics g ) {
      super.paintComponent( g );
      Graphics2D g2 = (Graphics2D)g;
      BufferedImage bi=getBufImg();
      g2.drawImage(bi, 0, 0, this.getWidth(), this.getHeight(), null );Is this more efficient or better form? Should I update my code everywhere?
    Also, the latter method seems to work the first time I call it, but I can't seem to change the image on an event like mouseEnter using code like this:
    public void mouseEntered(MouseEvent e) {
      Graphics g = this.getGraphics();
      Graphics2D g2 = (Graphics2D)g;
      BufferedImage bi=getBufImg();
      g2.drawImage(bi, 0, 0, this.getWidth(), this.getHeight(), null );
    }what's wrong?

    Is this more efficient or better form?
    No.
    Should I update my code everywhere?
    It depends on what you want to do. If you want to show an image then ImageIcon is an easy way. Override paintComponent when you want to do something other than simply display the image, eg, write text on top of the image or alter the image with things like rotation and scaling.
    Also, the latter method seems to work the first time I call it, but I can't seem to change the image on an event like mouseEnter using code like this
    Don't put painting code inside event code. Painting/drawing code belongs in an appropriate painting method. Use member variables in the enclosing class for state, manipulate these from your event code and set up your painting method to be able to accurately render this state at any time.
    stephensk8s is correct about the mouseEntered method. It works for components. So using a simple JLabel with ImageIcon is a carefree way to achieve rollover affects.
    Creating this kind of thing for custom graphics and images takes a little more effort. It all depends on what you are trying to do.
    Is there a good place to go to get a better understanding of this, or just ask on this forum?
    Ask when you need help.
    Resources that may be helpful to get started:
    Lesson: Writing Event Listeners
    Lesson: Performing Custom Painting
    How to Use Icons
    Lesson: Working with Images
    Core Java Technologies Tech Tips.

  • Z-value on imageicon/jlabel

    Hi wonder how to put a z-value on a imageicon or jlabel? (which to be on top, and second..etc)
    Thanks in advance!

    Swing related questions should be posted in the Swing forum.
    Use a [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]Card Layout or a [url http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html]LayeredPane.

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

  • Problem with findComponentAt highlighting wrong JLabel

    I've got a small 6 by 7 grid of jlabels that I would like to turn red if clicked on. In the japplet shown below, this works, sort of: it turns the label to its left red but not the label under the mouse. Any ideas on what I'm doing wrong? Thanks!
    MyApplet.java
    import javax.swing.JApplet;
    public class MyApplet extends JApplet
        MyPane2 pane = new MyPane2();
        public void init()
            getContentPane().add(pane);
    }MyPane2.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class MyPane2 extends JPanel implements MouseListener
        private static final int MAX_ROW = 6;
        private static final int MAX_COL = 7;
        private String whiteDot = ".\\petes\\brief3\\whiteDot.jpg";
        private String redDot = ".\\petes\\brief3\\redDot.jpg";
        private JLabel[][] myLabelGrid;
        private JPanel gridPane = new JPanel();
        public MyPane2()
            super();
            add(createLabelGridPane());
        private JPanel createLabelGridPane()
            gridPane = new JPanel();
            GridLayout myGridLO = new GridLayout(MAX_ROW, MAX_COL);
            myGridLO.setHgap(5);
            myGridLO.setVgap(5);
            gridPane.setLayout(myGridLO);
            gridPane.addMouseListener(this);
            myLabelGrid = new JLabel[MAX_COL][MAX_ROW];
            for (int row = 0; row < MAX_ROW; row++)
                for (int col = 0; col < MAX_COL; col++)
                    //myLabelGrid[col][row] = new JLabel(new ImageIcon(whiteDot));
                    myLabelGrid[col][row] = new JLabel("W");
                    gridPane.add(myLabelGrid[col][row]);
            return gridPane;
        public void mouseClicked(MouseEvent me)
            JPanel myPanel = (JPanel)me.getSource();
            System.out.println(findComponentAt(me.getX(), me.getY()));
            Component myComponent = findComponentAt(me.getX(), me.getY());
            if (myComponent instanceof JLabel)
                //((JLabel)myComponent).setIcon(new ImageIcon(redDot));
                ((JLabel)myComponent).setText("R");
            repaint();
        public void mouseEntered(MouseEvent arg0){}
        public void mouseExited(MouseEvent arg0){}
        public void mousePressed(MouseEvent arg0){}
        public void mouseReleased(MouseEvent arg0){}
    }[edited to use a label with "W" or "R" rather than images]
    Message was edited by:
    petes1234

    //  <applet code="FindComponentApplet" width="400" height="400"></applet>
    //      No html file necessary, just type
    //  appletviewer FindComponentApplet.java
    //      at the prompt and press enter.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FindComponentApplet extends JApplet
        public void init()
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(new FindComponentPane());
    class FindComponentPane extends JPanel implements MouseListener
        private static final int MAX_ROW = 6;
        private static final int MAX_COL = 7;
        Component lastSelected;
        public FindComponentPane()
            super(new BorderLayout());
            add(createLabelGridPane());
        private JPanel createLabelGridPane()
            JPanel gridPane = new JPanel(new GridLayout(MAX_ROW, MAX_COL, 5, 5));
            gridPane.addMouseListener(this);
            JLabel[][] myLabelGrid = new JLabel[MAX_COL][MAX_ROW];
            for (int row = 0; row < MAX_ROW; row++)
                for (int col = 0; col < MAX_COL; col++)
                    JLabel label = new JLabel("W", JLabel.CENTER);
                    label.setBorder(BorderFactory.createEtchedBorder());
                    myLabelGrid[col][row] = label;
                    gridPane.add(myLabelGrid[col][row]);
            return gridPane;
        public void mouseClicked(MouseEvent me)
            JPanel panel = (JPanel)me.getSource();
            Component component = panel.findComponentAt(me.getX(), me.getY());
            System.out.println(component.getClass().getName());
            if (component instanceof JLabel)
                if(lastSelected != null)
                    ((JLabel)lastSelected).setForeground(Color.black);
                ((JLabel)component).setForeground(Color.red);
                // Since there are gaps among the labels we need this in here.
                lastSelected = component;
            repaint();
        public void mouseEntered(MouseEvent arg0){}
        public void mouseExited(MouseEvent arg0){}
        public void mousePressed(MouseEvent arg0){}
        public void mouseReleased(MouseEvent arg0){}
    }

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

  • Set the size of an ImageIcon

    Hi,
    I have dispalyed a picture on a JLabel using an ImageIcon. But I do not know how to set the height and width of the picture being displayed. Plz tell me how to control the size of the picture.
    Thanks a lot,
    Chamal.

    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class X {
        public static GraphicsConfiguration getDefaultConfiguration() {
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gd = ge.getDefaultScreenDevice();
            return gd.getDefaultConfiguration();
        public static Graphics2D hintForBestQuality(Graphics2D g2) {
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            //etc...
            return g2;
        public static BufferedImage rescale(BufferedImage src, double factor) {
            int w = (int) Math.floor(src.getWidth() * factor);
            int h = (int) Math.floor(src.getHeight() * factor);
            int transparency = src.getColorModel().getTransparency();
            GraphicsConfiguration gc = getDefaultConfiguration();
            BufferedImage tgt = gc.createCompatibleImage(w, h, transparency);
            Graphics2D g2 = tgt.createGraphics();
            hintForBestQuality(g2);
            g2.drawRenderedImage(src, AffineTransform.getScaleInstance(factor, factor));
            g2.dispose();
            return tgt;
        public static void main(String[] args) throws IOException {
            URL url = new URL("http://java.sun.com/placeholders/duke_swinging.gif");
            BufferedImage image = ImageIO.read(url);
            BufferedImage bigger = rescale(image, 2.5);
            Icon icon = new ImageIcon(bigger);
            JLabel label = new JLabel(icon);
            JFrame f = new JFrame("X");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(label);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }

Maybe you are looking for

  • DoPost is not getting called in my servlet

    Hi All I have a servlet where I have doGet and doPost methods. My doGet is working but code written in my doPost is not getting fired.Please have a look : public class TestServlet extends HttpServlet { int count; public void init(ServletConfig config

  • Image Processor from Bridge CS5

    Lately, I have been getting this error message when trying to access the Image Processor (PS CS5)from Bridge CS5: "Sorry something major happened and I can't continue". I called Adobe support and was told that it might be related to third party plugi

  • Weblogic portal 10.3 - How to make JSF page to display different jspx page

    Hi, I am new to Weblogic Portal Technology. In my porject I am using trinidad jsf 1.1 and weblogic portal 10.3. I have an issue in changing the jspx path in the JSF portlet at runtime. My scenario is as given below. I have a left portlet and a right

  • How do I get my pics off iPad to free up memory

    I have an IPad with (16 gig) with wifi. I have a lot of pics on my iPad and need to get them off to free up memory to upgrade to the ios7. I have a windows pc. I down loaded ITunes app on the pc, but can not figure how to get them onto the pc. Would

  • Local help files for CS5 products (Illustrator in particular)

    I have read through the discussions, but I want to find a SIMPLE, STRAIGHTFORWARD way to set up my CS5 programs to access help files locally, rather than through the web. - I have found .PDF help files online, but there is no apparent way to link the