The Artima Developer Community
Sponsored Link

Java Answers Forum
Adding an Icon

2 replies on 1 page. Most recent reply: Feb 26, 2002 1:52 PM by Matt Gerrans

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
Barbara

Posts: 1
Nickname: bj
Registered: Feb, 2002

Adding an Icon Posted: Feb 26, 2002 7:41 AM
Reply to this message Reply
Advertisement
Hi! I'm a novice to JAVA, have spent a day trying to add an icon to a JButton, a JLabel, etc. I have even run an original Sun program. Everything functions fine, but the icon is not shown. I am beginning to think my installation is incomplete. Thank you for your help!
(cup.gif is in the same folder as my .java and .class files)
ImageIcon bird = new ImageIcon("cup.gif");
JButton button2 = new JButton(cup);
add(button2);


Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: Adding an Icon Posted: Feb 26, 2002 8:14 AM
Reply to this message Reply
Change the following line:
ImageIcon bird = new ImageIcon("cup.gif");
to
Icon bird = new ImageIcon("cup.gif");

The constructor for JButton needs an Icon object
public JButton(Icon icon)

ImageIcon implements the Icon interface so you can cast the ImageIcon creted with new ImageIcon("cup.gif") as an Icon.

Alternatively you might be able to do this:
JButton button2 = new JButton((Icon)cup);

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: Adding an Icon Posted: Feb 26, 2002 1:52 PM
Reply to this message Reply
Actually the problem was the method being used. The add() method is to add one component to another. What you really want to use is the setIcon() method where the add() method was used in the original post. Using the Icon-overloaded of version of the JButton constructor works fine too, but I don't think any casting is necessary -- you can pass the ImageIcon directly.

Flat View: This topic has 2 replies on 1 page
Topic: creating xml Previous Topic   Next Topic Topic: Applets

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use