JLabel Icon Updates

I am running a MYSQL query and assigning the values to Jlabels. Like this:
jLabel2.setText ( nameVal );I want to be able to assign the icons of the jLabels as well. Is this possible?

Same result. Here is the whole thing right from the tutorials:
//package components;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.UIManager;
import javax.swing.SwingUtilities;
* LabelDemo.java needs one other file:
*   images/middle.gif
public class LabelDemo extends JPanel {
    public LabelDemo() {
        super(new GridLayout(3,1));  //3 rows, 1 column
        JLabel label1, label2, label3;
        ImageIcon icon = createImageIcon("http://duke.kenai.com/iconSized/duke4.gif",
                                         "a pretty but meaningless splat");
        //Create the first label.
        label1 = new JLabel("Image and Text",
                            icon,
                            JLabel.CENTER);
        //Set the position of its text, relative to its icon:
        label1.setVerticalTextPosition(JLabel.BOTTOM);
        label1.setHorizontalTextPosition(JLabel.CENTER);
        //Create the other labels.
        label2 = new JLabel("Text-Only Label");
        label3 = new JLabel(icon);
        //Create tool tips, for the heck of it.
        label1.setToolTipText("A label containing both image and text");
        label2.setToolTipText("A label containing only text");
        label3.setToolTipText("A label containing only an image");
        //Add the labels.
        add(label1);
        add(label2);
        add(label3);
    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String URL,
                                               String description) {
        java.net.URL imgURL = LabelDemo.class.getResource(URL);
        if (imgURL != null) {
            return new ImageIcon(imgURL, description);
        } else {
            System.err.println("Couldn't find file: " + URL);
            return null;
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("LabelDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Add content to the window.
        frame.add(new LabelDemo());
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
          //Turn off metal's use of bold fonts
             UIManager.put("swing.boldMetal", Boolean.FALSE);
          createAndShowGUI();
}

Similar Messages

  • JLabel Icon Update Question

    Hi. I have created a jLabel that get's it's Icon updated via a value derived from a MYSQL query. The Icon1 value is a URL. My question is, if I do the MYSQL query and the URL doesn't change from the existing value, does the jLabel still go out and pull the image over? Or does it recognize that the URL is still the same and doesn't make an attempt at pulling the image over? Basically, I am asking this because I'm trying to determine the load on my webserver. Thank you for your help!
    image1.setIcon(icon1);

    Hi Daryl. Here is what I'm doing:
    protected static ImageIcon createImageIcon(String URL,
                                                   String description) {
            //java.net.URL imgURL = LabelDemo.class.getResource(URL);
            java.net.URL imgURL = null;
        try {
          imgURL = new java.net.URL(URL);
        } catch (Exception e) {
          //Logger.getLogger(LabelDemo.class.getName()).log(Level.SEVERE, null, ex);
            if (imgURL != null) {
                return new ImageIcon(imgURL, description);
            } else {
                System.err.println("Couldn't find file: " + URL);
                return null;
    ImageIcon icon1 = createImageIcon("https://www.website.com/images/" + dateVal + "/thumbs/" + image2Val + "",
                       image1.setIcon(icon1);

  • File icon update crashes finder

    In Panther: I'll have a finder window open in icon mode and I resave a file in Photoshop and when the icon updates the finder window crashes.
    Anything I can do about it other than a work around?

    Have you tried restart and/or Repair Permissions
    george

  • Dock icon update current date without having iCal running?

    Hello, minor thing - I typically leave my computer on all the time. I don't use iCal too often but I have the icon in the dock. I am wondering if there is a way to have the dock icon update without launching iCal? It would be nice that the current date is displayed when I view the dock. I guess I could schedule iCal to be launched and then quit once a day. I don't know, any suggestions?

    I have a few suggestions.
    1) This is a free alternative: http://www.objectpark.net/mcc.html
    2) Search MacOSXhints for a way to change the dock date daily. I read a hint there a few months ago for doing this: http://www.macosxhints.com/
    3) Wait for the next iCal as I would be surprised if Apple doesn't build this in to iCal 3 given how many times folks ask this question.
    4) You'll like suggestion #1.

  • JLabel (icon Image) without picture?

    I am make applet containing JLabel (Icon Image). When I run this applet from server and used image-file "middle.gif" (from tutorial) - there was all Ok. After this I changed color of image on MS Photo Editor and now I get JLabel without icon and there is no errors. I don't understand what happens? Anybody know what is it?

    Of course. In directory "Images" I have follow files:
    green.gif
    middle.gif
    red.gif
    Files green.gif and red.gif are middle.gif but pictures on them have respective colors. This colors I get using MS Photo Editor.
    import javax.swing.*;
    import java.awt.*;
    import java.net.*;
    public class tLabImage extends JApplet{
    public void init () {
    JFrame f=new JFrame();
    URL url=null;
    try {
    // url=new URL("http://10.1.1.6/Images/middle-1.gif");
    url=new URL("http://10.1.1.6/Images/green.gif");
    catch (MalformedURLException e) {System.out.println (e.getMessage());}
    Image image=getImage(url);
    ImageIcon icon=new ImageIcon(image);
    JLabel l=new JLabel ("text", icon, JLabel.LEFT);
    f.setLocation(200,300);
    f.getContentPane().setLayout(new GridLayout(0,2));
    f.getContentPane().add(l);
    f.pack();
    f.setVisible(true);
    When I run this programm I get JLabel without icon (only text). Why? Who can answer?

  • Cant change JLabel icon with setIcon a second time???

    Hey all,
    I have drawn 21 cards on my GUI - then as a user selects one of three columns via a radio button and subsequent Submit button, the deck reshuffles itself, and is THEN supposed to change all the labels to the new cards in their New order.
    All the code is good up until the point where it tries to reset the icon - and then I get a
    "AWT-EventQueue-0" java.lang.NullPointerException
    pointing to the line of my first Label that I am changing.
    I am trying to use the same settings as I did in the initial setting and think that maybe this could be my problem, but cannot find a proper setting in the Interface.
    My initial settings are this :
    for (i=0; i < 7; i++)
              cardscol1.setIcon(new ImageIcon("images\\" + deck.get(i)));
    cardscol2[i].setIcon(new ImageIcon("images\\" + deck.get(i + 7)));
    cardscol3[i].setIcon(new ImageIcon("images\\" + deck.get(i + 14)));
    THEN I tried this again (( INSIDE MY buttonHandler ))
    for (i=0; i < 7; i++)
                            j=0;
                            cardscol1.setIcon(new ImageIcon("images\\" + deck.get(j)));
    j++;
    cardscol2[i].setIcon(new ImageIcon("images\\" + deck.get(j)));
    j++;
    cardscol3[i].setIcon(new ImageIcon("images\\" + deck.get(j)));
    j++;
    And this is where I get the NULL POINTER EXCEPTION -- help??
    ****UPDATE:
    I cant access these Label PERIOD from within my Button Handler -- any idea why?

    OK -- the cardscol1 and 2 and 3 JLABEL arrays reference cards11, 12, 13, 14, etc. etc... THESE CARDS are within the initComponents class that is in a seperate class as well -- so that is probably my problem-- how do I get this submitButtonHandler class to see the cards that are in my initComponents class???
    AND THIS initComponents class is listed as PRIVATE!!! ((This is a class that the NetBeans GUI maker sets up -- very nice feature, but I cannot edit this class at all!))
    Message was edited by:
    tvance929

  • HT1369 My ipod is froze with itunes music icon and usb icon updated it

    When I decided to updated my ipod and error occur along the way now it is froze with itunes and usb icon on it. When I cut it off the icons is still there can't get it to go back to it natural screen. This is the 4th generation ipod with the camera should have not updated it. Not sure about ios number. The itunes program is working fine, update mess up my ipod not even on the itunes window.

    Restore the ipod.

  • Simulating animation by iterating - JLabel icon. ONLY  Working first time!

    I am "simualting" animation by changing the icon attribute of a JLabel. If I call the method from main, this works. It also seems to work (ie. the JLabel image changes on the screen as the icon attribute is changed in the program.) if I call it first from another or its own class one time, but not after that. What happens on subsequent calls is: The thread.sleep() is working (time passes), and the icon attribute of the JLabel is chaging (lblCaveActive.getIcon() for the JLabel returns the correct changed *.gif, but the images do not show up on the screen, until the last image, whatever I set it to be. I am pulling my air out over this little problem, which is the last lingering problem I am having with this project....I was wondering if you have seen this or have any ideas? I have tried lots of different things, including repainting and such. If you have a clue concerning this, please please please advise, o wise one.
    * simulates animation: ex. Wumpus approaching to eat the
    * player, bat appraoching to transport player
    * @param: int numPics - number of pictures to loop through
    * @param: String picNamePreface - filenames must be "*0.gif" through
    * picNamePreface + numPics + ".gif".
    * Send the "*" portion into this arg
    * @param: int milliSecSleep - seconds for the thread to sleep between
    * pictures
    private void animateMeetHazard(int numPics, String picNamePreface,
    int milliSecSleep)
    try
    for (int i = 0; i <= numPics; i++)
    caveCurrentIcon = new ImageIcon(picNamePreface + i + ".gif");
    lblCaveActive.setIcon(caveCurrentIcon);
    Thread.sleep(milliSecSleep);
    catch (InterruptedException e){}
    --A very tired girl.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Something like
    private void animateMeetHazard(int numPics, String picNamePreface,
    int milliSecSleep)
    try
    SwingWorker workHard = new SwingWorker()
    public Object construct()
    for (int i = 0; i <= numPics; i++)
    caveCurrentIcon = new ImageIcon(picNamePreface + i + ".gif");
    lblCaveActive.setIcon(caveCurrentIcon);
    Thread.sleep(milliSecSleep);
    return null;
    public void finished()
    workHard.start();
    catch (InterruptedException e){}
    Not really sure if the Thread.sleep() will throw you out and give you the same problems .. but it mightn't ;)

  • JLabel not updating text in GUI

    i've spent about an hour trying to get my label to update from another class. i set the label to public and i tried to invoke setText() on it from the other class, but it doesnt change it in the GUI. i printed the getText() method of the label and it's identical to what i tried to set it to be, but it just isnt displaying the correct text.
    i know to update in the GUI it needs to repaint itself, but this is automatic for setText() and it is working for the local calls to setText().
    i have a method
         public void setStatus(String text)
              status.setText(text);
         }that should do exactly what i want, but it only works when called from its own class..... HELP

    hey,
    just a little example...
    //first little class with the label in it! and a getter for the label.
    public class LabelPanel extends JFrame {
         private static  JLabel label;
         public LabelPanel(){
              initGUI();
         private void initGUI() {
              label = new JLabel("old text");
              JPanel panel = new JPanel();
              ButtonPanel buttonPanel = new ButtonPanel();
              panel.add(buttonPanel.getPane());
              panel.add(label);
              setContentPane(panel);
         public static void main(String[] args)
              // Schedule a job for the event-dispatching thread:
              // creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
          * Create the GUI and show it.
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new LabelPanel();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setTitle("test");
              // Display the window.
              frame.pack();
              frame.setVisible(true);
            // gets the label
         public static JLabel getLabel() {
              return label;
    //second class just a button that changes the label
    public class ButtonPanel implements ActionListener{
         private JPanel pane;
         private JButton button;
         public ButtonPanel(){
              init();
         private void init(){
              button = new JButton("change");
              button.addActionListener(this);
              pane = new JPanel();
              pane.add(button);
         public void actionPerformed(ActionEvent e) {
              String cmd = e.getActionCommand();
              if(cmd.equals("change")){
                   button.setText("done");
                            //get the label and set the new text
                   LabelPanel.getLabel().setText("new text");
              }else if(cmd.equals("done")){
                   button.setText("change");
                            //get the label and set the new text
                   LabelPanel.getLabel().setText("old Text");
         public JPanel getPane() {
              return pane;
    }hope that helps!!! :)

  • Putting JLabel icon images in .jar

    I'm trying to make my program display JLabels with icons. This works successfully, however it relies on local files. I want to distribute the jar file only, so I was hoping there was a way I could put the images in the package or subfolder within the jar file and have the code reference the pictures there. Is there a way to do this. The code I'm using now is as follows :
    if(status.equals("good")){
         return (new JLabel(new ImageIcon("images/OK.gif")));
    }else //if(status.equals("bad"))
    return (new JLabel(new ImageIcon("images/FAIL.gif")));
    Thanks for any advice you my have.

    Putting both the class files and the images files in the same jar definitely works.
    I do it all the time. The simplest thing to do is to put the images in the same folder
    as the class file that accesses them, then jar up the lot. Your code should look like:
    URL url = this.getClass().getResource("your_image.jpeg");
    Icon icon = new ImageIcon(url);
    //etc...In fact, you should always code in this way: this code works will a jarred or unjarred program.
    Because with file names, however: jar file names are always case sensitive.

  • JButton icon update problem

    Hi
    I'm creating a JPanel with some JButtons set to different icons to create a seatmap. There are two kinds of JButtons: Existing Seat, Available Seat. The code is set up to allow an Available to switch icon to Existing if pressed. In that case the previous Existing becomes available switching its own icon.
    The problem is that the first time the screen is created all Available status buttons work correctly, but the first selected Existing seat does not go available upon choosing a new seat. If the first existing seat is pressed before pressing an available things work perfectly.
    To give an example, when the screen is first created seat 33C is currently selected as the existing seat and seats 32A and 34C are available. If the first button I press is 32A it switches icons to become Existing but 33C does not go to Available. Now if I press any of the other available seats such as 34C 32A becomes available and the new selected seat (34C) becomes Existing. All this time 33C does not change icons - stays at Existing - so I have two Existing seats showing.
    However if I click on 33C at any time it becomes "Live" - starts behaving correctly.
    Any suggestions/ advice much appreciated. have enclosed code snipped below:
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    Iterator it2 = thisRow.values().iterator();
    while (it2.hasNext()) {
    final Seat s = (Seat) it2.next();
    thisSeat = s.row + s.col;
    final JButton seatButton = new JButton();
    seatButton.setOpaque(false);
    seatButton.setBorderPainted(false);
    seatButton.setIcon( (Icon) iconTable.get(s.status));
    if (thisSeat.equalsIgnoreCase(currSeatStr)) {
    seatButton.setIcon( (Icon) iconTable.get(s.STATUS_EXISTING));
    s.status = s.STATUS_EXISTING;
    innerClassHelperInstance.prevSeatButton = seatButton;
    innerClassHelperInstance.prevSeat = s;
    seatButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    if (s.status.equalsIgnoreCase(s.STATUS_AVAILABLE)) {
    tmpExistingSeatLabel.setText(s.row + s.col);
    innerClassHelperInstance.prevSeat.status = s.
    STATUS_AVAILABLE;
    innerClassHelperInstance.prevSeatButton.setIcon( (Icon)
    iconTable.get(s.STATUS_AVAILABLE));
    seatButton.setIcon( (Icon) iconTable.get(s.STATUS_EXISTING));
    innerClassHelperInstance.prevSeatButton = seatButton;
    innerClassHelperInstance.prevSeat = s;

    Hi! How can I change the icon attached to a JButton
    when running the application? By calling setIcon.
    setIcon method doesn't work.. Yes it does.
    Not even if I put an updateUI() after that..There is no need for that as the button will be updated automatically. So you must be doing something wrong. To begin with, maybe you can explain what you mean by "doesn't work".

  • JLabel Icon Size

    Hi,
    I wanted to use an image as a background for my JPanel. I didn't want to fuddle around with custom painting so I just created a Jlabel with an icon, and added that to the panel. My problem is that, the icon is always the same size, no matter the size of the label. Any extra space just gets filled with the getBackground() color. How can I adjust the icon's size inside the JLabel?
    Thanks a lot!

    Check out these threads:
    [url http://forum.java.sun.com/thread.jsp?forum=31&thread=286424&start=3&range=1]Painting an Image.
    [url http://forum.java.sun.com/thread.jsp?forum=57&thread=417669&start=2]Scaling an Image.

  • Icon Update & DefaultLookandFeel Problems

    I am trying to produce an application with an icon that changes to show the status of the users progress - similar to a traffic light system.
    My problem is getting the icon to change.
    I have a button set with a action listener:
              loadButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                               statusPanel.setStatus(StatusIndicator.WSDL_VALIDATE);                              
              });The statusPanel object is an instance of a class StatusIndicator that extends a JPanel.
    The setStatus method called by the button's action listener is
                 public void setStatus(String status)  {
              if (status == NO_INPUT || status == WSDL_VALIDATE || status == MODEL) {
                   System.out.println("Changing status to " + status);
                   lights = new ImageIcon(imagesDir + separator + status);
                   this.status = new JLabel(lights);
                   this.status.repaint();
                   this.status.revalidate();
                   this.getParent().validate();
                   this.validate();
              this.repaint();
              this.revalidate();
         }the NO_INPUT variables are final variables that represent the (correct) location of the icons.
    I am pretty sure the ImageIcon declaration is working correctly because it loads the correct red light icon at startup.
    When I press the button, I get the messages from the print statement printed out correctly but the display doesn't change?
    What am I doing wrong?
    Also on an another niggle, i have JFrame.setDefaultLookAndFeelDecorated(true); set in my program but this doesn't apply to the first window, when I do File -> New (within the same JVM) I get a new window with the default look and feel applied?
    What could be causing these 2 problems?
    Any help very much appreciated.
    Thanks

    Instead of this: this.status = new JLabel(lights);try this: this.status.setIcon(lights);By the looks of your example, you are just resetting a local variable to a JLabel w/o adding the new label to the layout.
    JFrame.setDefaultLookAndFeelDecorated(true); is static and should be called before you show your first window.
    If that doesn't work, try setting the lookandfeel
    You have to set the lookandfeel prior to showing your frame.
            try
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch( Exception e )
                logger.error("Could Not set Look and Feel", e);
            JFrame yourFram  = new JFrame("Test");

  • JLabel Icon from online image?

    I am writing a program (purely for curiosity-sake) that searches the automotive section of a popular online classifieds website, retrieves the 20 latest ad posts (the 20 newest cars posted), and displays the title ("1969 Mustang, great shape! Must sell!", etc.), price, description, and post time/date in labels in my program (using Swing). This all works fine so far, but one feature I would like to implement is causing me some grief. Each online posting has a thumbnail image which I would like to retrieve and display in my program. I would like to use a JLabel, then set the "icon" property to reference the online image. I don't wish to have hundreds of thumbnails caches in programs' project folder, so is there a way to set the label's icon property to not only an external image, but an online one? I am using NetBeans 6.0.1 and JDK1.6.0_03. In NetBeans, using the Properties window on the right, the "icon" property allows me to choose an external, but local, image -- this doesn't help much. All online thumbnails are the same size (64x48), and my label is the same size (it will be strictly an image displayer, no text). Any help greatly appreciated!

    ImageIO could load from the URL of the image of your interest.

  • JLabel icon position question

    I want to have a JLabel with text and an icon. I want the text to be positioned on the left and I want the icon on the right. My question is: Is this possible and if so how?

    RTFM
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JLabel.html#setHorizontalTextPosition(int)

Maybe you are looking for

  • Add Command button not in the Database Expert: VS2003

    We are using VS2003 and the bundled version of Crystal Reports.  We have no plans of upgrading right now, unless we have to. What I'm trying to do should be simple... We have an existing report that lists incomplete orders, including invoice# and ite

  • Very Urgent pls help me

    Hi in sap script in data fiels is &komvd-kbetr(T10.2)&/M  my output for this field is 2500.00 /M I need to remove the space b/w 2500.00 and /M. I tried all the methods using (C). it is not working. i just changed the decimal place to &komvd-kbetr(T7.

  • Messages Deleting By Themselves

    My messages are deleting by themselves, slowly but surely. I have my phone set to save them 'forever' and i always have done, so i'm not sure why this is happening. I have a Blackberry Curve 3G. Any ideas?

  • Is it safe to upgrade my Iphone4?

    I have an iphone4 with MC603ZP which is tagged factory unlocked. Was wondering if it would be safe to upgrade it to IOS5 using my itunes? Heard that if i upgrade it i would lose its unlock status?

  • Migrating from NCS 1.1.2 to Prime 1.2? Possible?

    According to this: http://www.cisco.com/en/US/docs/net_mgmt/prime/infrastructure/1.2/quickstart/guide/cpi_qsg.html#wp73107 it mentions that migrating from NCS 1.1.2 to CPI 1.2 isn't possible. How can I get around this?