Jbutton icon in Applet

Hi!
i create an applet with somu buttons.
How can i insert a file .gif or .png in a jbutton icon.
where i have to put my gif files?
Sorry for my english.
thanks a lot

import java.awt.*;
import javax.swing.*;
/** Simple example illustrating the use of JButton, especially
*  the new constructors that permit you to add an image.
*  1998-99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
public class JButtons extends JFrame {
  public static void main(String[] args) {
    new JButtons();
  public JButtons() {
    super("Using JButton");
    Container content = getContentPane();
    content.setBackground(Color.white);
    content.setLayout(new FlowLayout());
    ImageIcon cup = new ImageIcon("cup.gif");
    JButton button1 = new JButton(cup);
    content.add(button1);
    pack();
    setVisible(true);
    try {
      jbInit();
    catch (Exception ex) {
      ex.printStackTrace();
  private void jbInit() throws Exception {
}This is some example code I copied off of the internet and edited for a very basic example. The file cup.gif is located in the correct directory and this file will compile from the command line and show the button graphic but from not JBuilder. Does anyone have any ideas? Thank you.

Similar Messages

  • Using animated GIF as JButton icon

    Hi,
    I am trying to use an animated gif as an icon in a JButton.
    Everything works as it should except the animation is static!!
    Screenshots and code are at:
    http://www.beammicrosystems.com/Java/JButton.html
    Anyone got any good ideas?
    Regards,
    Andrew

    well i think you can do this in a label you can watch for a animation like you want a gif so my idea is that you should just make the label as a button and them :
    JLabel label = new JLabel();
    label.setIcon = new ImageIcon("name.gif");
    and put it the setBounds
    label.setBounds(x,y,long,tall);
    and if you want that looks like a button just do this
    label.setBorder(BorderFactory.createRaisedBevelBorder());
    thats all.

  • Set JButton Icon

    Hi!
    I have a small problem!
    I have a JInternalFrame and on it I place a JPanel and on the panel a JButton.
    I try to place an image on the button
    image = new ImageIcon( "8.gif" ).getImage();
    ImageIcon icon = new ImageIcon(image);
    button.setIcon( icon );
    I use Jbuilder 6 and JDK 1.4
    When I used JDK 1.3 all worked fine.
    Now under 1.4 it does not display the image anymore. Why?
    Does anyone have a solution?
    Thanks!!

    try this :
    ClassLoader cl = this.getClass().getClassLoader();
    ImageIcon icon = new ImageIcon(cl.getResource("8.gif"));
    button.setIcon(icon);

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

  • Jtree Icons in Applet

    I've used Jtree in a frame with diffrent icons for each level. Now I want to use that Jtree in applet but all the icons disappear! I've used UIManager to chane default icons. How can I use icons in a applet for Jtree?
    Thanks for your help

    Try this url http://www.cscc.de/books/swingbook/files/uts2/Chapter17.pdf
    to change the TreeCellRenderer.

  • JOptionPane JButton Icon

    Hi,
    Does anyone knows how to set icons in the JOptionPane buttons ?
    I use this but when I click it never closes the dialog.
    JButton[] options = new JButton[3];
    options[0] = new JButton("B1");
    options[1] = new JButton("B2");
    options[2] = new JButton("B3");
    int n = JOptionPane.showOptionDialog(null,
    "Would you like to replace it ?",
    "Question",
    JOptionPane.YES_NO_CANCEL_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null,
    options,
    null);
    System.out.println(n);
    Thanks.

    Use this :
    Icon[] options = { new ImageIcon("yes.gif"),new ImageIcon("no.gif"), new ImageIcon("cancel.gif")};
    int res = JOptionPane.showOptionDialog(null, "Select a button", "title", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);I hope this helps,
    Denis

  • JButton Icon Problem

    Hi! How can I change the icon attached to a JButton when running the application? setIcon method doesn't work.. Not even if I put an updateUI() after that.. Thanks!

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

  • Question about JButton icons

    I'm displaying a panel with three JButtons in one row, each of them displaying an icon. Each has an action listener registered to it. I want to change the icon when the button is pushed to reflect a different status. I remove the button from the panel, replace it with the new icon, then redisplay it. The problem is, the new button is added to the panel at the end of the row, and the remaining buttons are moved over. Is there any way I can just replace the old icon with the new one and redisplay the button without removing it from the panel and replacing it? It is important that I preserve the sequence in which the buttons are displayed.

    4merSnake wrote:
    If I do the "remove" and use the offset as you demonstrated, it works. If I just use the offset, it actually adds another button to the panel. The old one has to be removed first.
    Unless there's an easier way ...Again, there is: just swap icons. Here is an SSCCE to illustrate what I am proposing. This small app creates an array of 8 ImageIcons and swaps a buttons icon on press of a button. It is currently set up for 8 small images named image00.jpg to image07.jpg located at IMAGE_PATH = "src/dy08/m02/a/images/"; Just copy this program, paste it, have an a couple of same-sized and named images available, change the program's constants accordingly, and run.
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.io.IOException;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    * creates an array of ImageIcons and swaps a button's icon with each
    * press of the button
    * @author Pete
    * 4/28/08
    public class SwapIcons
        // ** these will have to change depending on location, name, size and number of images
        private final static String IMAGE_PATH = "src/dy08/m02/a/images/";
        private static final String IMAGE_NAME = "image";
        private static final String IMAGE_EXTENSION = ".jpg";
        private static final Dimension IMAGE_SIZE = new Dimension(180, 115);
        private static final int ICON_COUNT = 8;
        private JButton button = new JButton();
        private ImageIcon[] icons = new ImageIcon[ICON_COUNT];
        private int iconIndex = 0;
        public SwapIcons()
            NumberFormat nf = new DecimalFormat("00");
            for (int i = 0; i < icons.length; i++)
                try
                    icons[i] = new ImageIcon(ImageIO.read(new File(IMAGE_PATH + IMAGE_NAME +
                            nf.format(i) + IMAGE_EXTENSION)));
                catch (IOException e)
                    e.printStackTrace();
            button.setPreferredSize(IMAGE_SIZE);
            button.setIcon(icons[iconIndex]);
            button.addActionListener(new ActionListener()
                @Override
                public void actionPerformed(ActionEvent e)
                    buttonAction(e);
        private void buttonAction(ActionEvent e)
            iconIndex++;
            iconIndex %= icons.length;
            button.setIcon(icons[iconIndex]);
        public JComponent getButton()
            return button;
        private static void createAndShowUI()
            JFrame frame = new JFrame("SwapIcons");
            frame.getContentPane().add(new SwapIcons().getButton());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }

  • Loading icons during applet class init

    I load a bunch of icons thusly:
        ImageIcon[] typeIcons = {
            null,
            createImageIcon("context_icon", "Context"),
            createImageIcon("featureset_icon", "featureset"),
            createImageIcon("format_icon", "format"),
            createImageIcon("raster_icon", "grid"),
            createImageIcon("projection_icon", "projection")
        static ImageIcon createImageIcon(String name, String alt) {
            URL url = FeatureEditor.class.getResource(name + ".png");
            if(url == null)
                throw new IllegalArgumentException("No such image as " + name);
            return new ImageIcon(url, alt);
        }And display them as table cells.
    That works ok, but why does it go screwy on me if I make the typeIcons array static? (The TableCellRenderer complains that the objects are of the wrong type).
    I can't see why icon loading can't be initiated during class initialisation rather than in object initialisation.

    Where the method is defined in the source code won't help- it will get called during the initialisation of the array just as before. Is there really no other class object available that you can use instead for the base of your resources? If there's nothing else in your package, then use Object.class and give the full path, rather than a relative one (assuming you're using the default class loader).
    Pete

  • Applet jbuttons array

    Hi!I m trying to do this!If jbutton1 pressed and then jbutton2 pressed ,then if jbutton4 pressed jlabel4.setText("correct").Can you please help me?Thank you.
    [public class Icons extends Applet implements ActionListener{
      ImageIcon myIcon1 = new ImageIcon("eikones/image1.gif");
      ImageIcon myIcon2 = new ImageIcon("eikones/image2.gif");
      ImageIcon myIcon3 = new ImageIcon("eikones/image3.gif");
      JButton jButton1 = new JButton();
      JButton jButton2 = new JButton();
      JButton jButton3 = new JButton();
      JButton jButton4 = new JButton();
      FlowLayout flowLayout1 = new FlowLayout();
      JLabel jLabel1 = new JLabel();
      JLabel jLabel2 = new JLabel();
      JLabel jLabel3 = new JLabel();
      JLabel jLabel4 = new JLabel();
      int nextLabelToShowIcon =1;
      JButton[] p = new JButton[3];
      public void init() {
       p[0] = jButton1;
       p[1] = jButton2;
       p[2] = jButton4;
        jButton1.setPreferredSize(new Dimension(150, 25));
        jButton1.setIcon(myIcon1);
        jButton1.addActionListener(new Icons_jButton1_actionAdapter(this));
        jButton2.setPreferredSize(new Dimension(150, 25));
        jButton2.setIcon(myIcon2);
        jButton2.addActionListener(new Icons_jButton2_actionAdapter(this));
        jButton3.setPreferredSize(new Dimension(150, 25));
        jButton3.setIcon(myIcon3);
        jButton3.addActionListener(new Icons_jButton3_actionAdapter(this));
        jButton4.addActionListener(new Icons_jButton4_actionAdapter(this));
        jButton4.setPreferredSize(new Dimension(150, 25));
        this.setLayout(flowLayout1);
        jLabel1.getIcon();
        jLabel2.getIcon();
        jLabel3.getIcon();
        add(jButton1);
        add(jButton2);
        add(jButton3);
        add(jLabel1);
        add(jLabel2);
        add(jLabel3);
        add(jLabel4);
       add(jButton4);
    jButton1.addActionListener(this);
    jButton2.addActionListener(this);
    jButton3.addActionListener(this);
    jButton4.addActionListener(this);
      void jButton1_actionPerformed(ActionEvent e) {
        if (nextLabelToShowIcon==1)
          jLabel1.setIcon(myIcon1);
        else if (nextLabelToShowIcon==2)
          jLabel2.setIcon(myIcon1);
        else if (nextLabelToShowIcon==3)
          jLabel3.setIcon(myIcon1);
        else if (nextLabelToShowIcon==4)
      jLabel3.setIcon(myIcon1);
        nextLabelToShowIcon++;
      void jButton2_actionPerformed(ActionEvent e) {
        if (nextLabelToShowIcon==1)
          jLabel1.setIcon(myIcon2);
        else if (nextLabelToShowIcon==2)
          jLabel2.setIcon(myIcon2);
        else if (nextLabelToShowIcon==3)
          jLabel3.setIcon(myIcon2);
        else if (nextLabelToShowIcon==4)
      jLabel3.setIcon(myIcon2);
        nextLabelToShowIcon++;
      void jButton3_actionPerformed(ActionEvent e) {
        if (nextLabelToShowIcon==1)
          jLabel1.setIcon(myIcon3);
        else if (nextLabelToShowIcon==2)
          jLabel2.setIcon(myIcon3);
        else if (nextLabelToShowIcon==3)
          jLabel3.setIcon(myIcon3);
        else if (nextLabelToShowIcon==4)
      jLabel3.setIcon(myIcon3);
        nextLabelToShowIcon++;
      void jButton4_actionPerformed(ActionEvent e) {
    class Icons_jButton1_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton1_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton1_actionPerformed(e);
    class Icons_jButton2_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton2_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton2_actionPerformed(e);
    class Icons_jButton3_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton3_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton3_actionPerformed(e);
    class Icons_jButton4_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton4_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton4_actionPerformed(e);
    public void paint(Graphics g){
              super.paint(g);   }
    public void actionPerformed(ActionEvent e) {
         for(int i=0;i<p.length;i++){
      if(e.getSource()==p)
    jLabel4.setText("correct");
    else
    jLabel4.setText("wrong");
    /code] 

    include a class variable
    int buttonNumber = 0;
    then, include in the button's actionPerformed()
    button1
    buttonNumber = 1;
    button2
    if(buttonNumber == 1) buttonNumber = 2;
    else buttonNumber = 0;
    button 3
    buttonNumber = 3;
    button4
    if(buttonNumber == 2) jlabel4.setText("correct");
    buttonNumber = 4;
    needs testing, but something like the above should work OK

  • How do I retain Jbutton text for action event & set img icon on Jbutton

    I need to retain the text on my button as I use this to identify the action event in actionPerformed method when the button is pressed.
    Hoe do I add an image icon to the Jbutton without effecting this?
    [/b]
    class CalcPanel extends JPanel
        implements ActionListener, CurrencyVals
    //currency panel data members
        JButton[] cb = new JButton[4];
    JPanel cbkeys = new JPanel(new GridLayout(4,1));
    //Toolkit tk = Toolkit.getDefaultToolkit();
        //Image img = tk.getImage("D:/temp/ausflag.jpg");
    public CalcPanel(){
    ImageIcon b = new ImageIcon("D:/temp/ausflag.jpg","AUS");
        cb[AUS]= new JButton(b);  //cb[AUS]= new JButton("AUS");
          cbkeys.add(cb[AUS]);
          cb[AUS].addActionListener(this);
    setLayout(new BorderLayout());
        add(display, BorderLayout.NORTH);
        add(keys, BorderLayout.CENTER);
        add(cbkeys, BorderLayout.EAST);
        add(label, BorderLayout.SOUTH);
        public void actionPerformed(ActionEvent evt){
          Object source = evt.getSource();
          int id;
          if (keyBoard) {
            if (source instanceof JButton) {
              String s = ((JButton)source).getText();
    [/b]Regards
    Synfield

    if(keyBoard) { ??! [/b]... do have cause to feel flattered?
    Copy and paste this and save a small eg;- 25px high x 50px wide Jpeg image in the same file and call it "new.jpg", then study it, this posted program (again?) to see where your code went astray.
    THEN, figure out what you want to do with your code ...keep at it!
    Sue x
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ButtonIcon extends JFrame implements ActionListener {
    String []str ={"abc","def","ghi","jkl","mno","pqr","st","uvw"};
    JButton b[] = new JButton[str.length];
       JButton on = new JButton("ON");
       JButton off = new JButton("OFF");
       JButton picture;
       JPanel panel;
       String str2="";
       Font font = new Font("Comic Sans MS" ,0, 14);
       boolean keyBoard;
       ImageIcon icon = new ImageIcon("new.jpg");
    public ButtonIcon(){
       Container c = getContentPane();
       panel = new JPanel();
       panel.setLayout(new FlowLayout());
       picture = new JButton(icon);
       for (int j=0; j<=str.length-1; j++){
             b[j]= new JButton(str[j]);
             b[j].setFont(font);
             panel.add(b[j]);
             b[j].addActionListener(this);
       on.addActionListener(this);
       off.addActionListener(this);
       panel.add(on);
       panel.add(off);
       panel.add(picture);
       c.add(panel);
       public void paint (Graphics g) {
          super.paint (g);
          Graphics2D G = (Graphics2D) g;
          G.setColor(Color.red);
          G.setFont(font);
          G.drawString(str2, 25, 150);
    public void actionPerformed(ActionEvent evt){
        String command = evt.getActionCommand();
        if (keyBoard) {
           if (evt.getSource() instanceof JButton ) {
               str2 += command;
           if (evt.getActionCommand().equals("OFF")) str2 = "";
        if(command.equals("ON")) keyBoard = true;
        if(command.equals("OFF")) keyBoard = false;
    repaint();
    public static void main (String []args){
       ButtonIcon boo = new ButtonIcon();
       boo.setSize(300,200);
       boo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
       boo.setVisible(true);

  • Icon on JButton

    I'm having an odd problem. Seemingly, I've done mostly everything correctly, but something must be wrong somewhere.
    I'm trying to make JButtons with icon on them. I've made one, but the icon won't show. Here's my code:
              ImageIcon selectedIcon = new ImageIcon("selected.png", "Selected Menu");
              JButton characterScreenIcon = new JButton(selectedIcon);Now, that one actually works. But when I try to use setAction() on it, the icon disappears. This is the setAction line:
              characterScreenIcon.setAction(new ShowCharacterScreen());And here is the ShowCharacterScreen class:
         public class ShowCharacterScreen extends AbstractAction {
              public ShowCharacterScreen() {
                   super();
              public void actionPerformed(ActionEvent e) {
                   JButton icon = (JButton)(e.getSource());
                   icon.setIcon(selectedIcon);
                   JOptionPane.showMessageDialog(frame, "Button 1 pressed");
         }Now, it is worth noting that the action does work perfectly fine. I get the Dialog box. It's just the icon disappears when I use setAction() on it.
    I would like to know why this happens, so I can figure out how to fix it.

    hii,
    are you meaning this one ??? --->
    import java.awt.*;
    import java.awt.event.*;
    import java.io.BufferedInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import javax.swing.*;
    class TerraGUI {
        //GUI Fields
        static JFrame frame = new JFrame("TWOReborn");
        JPanel mainPane;
        JPanel characterPane;
        ImageIcon nonSelectedIcon;
        ImageIcon selectedIcon;
        public Container createContentPane() {
            mainPane = new JPanel();
            characterPane = new JPanel();
            characterPane.setPreferredSize(new Dimension(218, 442));
            characterPane.setBorder(BorderFactory.createLineBorder(Color.black));
            Image ViewMmImage = ImageViewMmLoader.getImage(TerraGUI.class, "resources/passed.png");
            Image ViewMmImage1 = ImageViewMmLoader.getImage(TerraGUI.class, "resources/failed.png");
            selectedIcon = new ImageIcon(ViewMmImage);
            nonSelectedIcon = new ImageIcon(ViewMmImage1);
            JPanel controlsAndStatus = new JPanel();
            JButton characterScreenIcon = new JButton();
            characterScreenIcon.setIcon(selectedIcon);
            characterScreenIcon.setMargin(new Insets(0, 0, 0, 0));
            characterScreenIcon.setAction(new ShowCharacterScreen());
            controlsAndStatus.add(characterScreenIcon);
            characterPane.add(controlsAndStatus);
            mainPane.add(characterPane);
            return mainPane;
        private static void createAndShowGUI() {
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setResizable(false);
            TerraGUI terra = new TerraGUI();
            frame.getContentPane().add(terra.createContentPane());
            frame.pack();
            frame.setVisible(true);
        public class ShowCharacterScreen extends AbstractAction {
            private static final long serialVersionUID = 1L;
            public ShowCharacterScreen() {
                super("", selectedIcon);
            public void actionPerformed(ActionEvent e) {
                JButton icon = (JButton) (e.getSource());
                icon.setIcon(null);
                icon.setIcon(nonSelectedIcon);
                JOptionPane.showMessageDialog(frame, "Button 1 pressed");
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    final class ImageViewMmLoader {
        private ImageViewMmLoader() {
        public static Image getImage(Class<?> relativeClass, String filename) {
            Image returnValue = null;
            InputStream is = relativeClass.getResourceAsStream(filename);
            if (is != null) {
                BufferedInputStream bis = new BufferedInputStream(is);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    int ch;
                    while ((ch = bis.read()) != -1) {
                        baos.write(ch);
                    returnValue = Toolkit.getDefaultToolkit().createImage(baos.toByteArray());
                } catch (IOException exception) {
                    System.err.println("Error loading: " + filename);
            return returnValue;
    }... kopik

  • JButton with Icon - when pressed moves Icon

    When I press on a JButton which contains a icon then the icon is moved a little bit each time I press. Can I disable that?
    I need to place clickable images. Is a JButton the best method for this?

    URL url = this.getClass().getResource("weiher_original.jpg");
    ImageIcon icon = new ImageIcon(url);
    btnIcon = new JButton(icon);
    btnIcon.setSize(new Dimension(icon.getIconWidth(), icon.getIconHeight()));
    btnIcon.setBorderPainted(false);
    btnIcon.setFocusPainted(false);
    getContentPane().add(btnIcon);Now if you press on the icon the image moves a few pixels until the mouse is released.

  • Icons in JButtons

    Hi everybody!!
    Someone can tell me if this is correct???
    I wanna put some Icons in my buttons, I have a directory where I stored that images.
    The code I use to add the images is...
    Button butValue=new JButton();
    Icon icon=new ImageIcon("/nombre/images/purify.jpg");
    butValue.setIcon(icon);
    The classpath is set to the directory where is nombre directory.
    It works well at home, but when I tried to run my application in other computer the images aren't loaded.
    Someone knows the solution???
    Thanks a lot

    I'm not sure what your directory structure is but I believe you should not use the leading "/" when specifying the file location. I think the file it is looking for is "c:/nombre/images/purify.jpg"
    If your class is in a directory: c:/java/test. The by removing the "/" I think it will look for a file called "c:/java/test/nombre/images/purify.jpg".
    If that doesn't work then the easiest way to test you program is to move the image into the same directory as the class and just use "purify.jpg" as the filename.

  • My applet doesn't run in a browser.

    I written the following code:
    import javax.swing.*;
    public class Logo extends JApplet
         JButton button ;
         Icon icon;
         JPanel panel;
         public void init()
              icon = new ImageIcon("smilogo.gif");
              button = new JButton(icon);
              panel = new JPanel();
              panel.add(button);
              getContentPane().add(panel);
    I also have my html file with the code :
    <HTML>
    <HEAD></HEAD>
    <BODY >
    <CENTER>
    <APPLET code = "Logo.class" width = "100" height = "100"></APPLET>
    </CENTER>
    </BODY>
    </HTML>
    when I run the html file with the appletviewer the image gets loaded like I
    expect it to. But when I run the file in a browser (IE version 5)after converting
    it using the HTMLConverter, the image doesn't load.
    What could be the problem. The code was compiled with J2sdk1.4.0.

    It's a JApplet, it needs the java plug in....
    If you've already got the plugin installed you'll just need to change the tag you're using to load the applet... it'll either be an embed tag or an object tag.. (embed for Netscape, Object for IE)...

Maybe you are looking for

  • HP Envy 6 - Boot Loop following Bios Update

    Hi All,  Having spent the better half of tonight trying to resolve an issue whereby my HP Envy 6 1232SA was stuck in a loop after what I thought was a failed bios update.  I received a message saying an UPDATE for my bios was available. I installed t

  • How do I set iCal so that my alarms go off when in sleep mode?

    I'm pretty sure that I can set iCal to open a program (iTunes) as an alarm while the computer is in sleep mode but I can't find the setting. This morning it didn't go off while in sleep mode. Does anyone know how?

  • Mysites 'change the look' back to default

    Hi - I recently attempted to change the look of mysites in our environment.  This worked, however it removed the person image from the upper left hand corner.  I would like to 'undo' this change, but can't seem to figure out how.  I would like mysite

  • Output forrmats for SAP documents

    Hi, I am trying to set up our SAP system such that all SAP documents are sent with HTML attachments. I have gone into transaction SCOT and under the 'Output formats for SAP documents' section, I tried to select the HTM option for SAPSCripts/Smart For

  • What Type Of File?

    I have defeated the format monster. The format monster being that Adobe Premiere Elements 10 will not support two videos at once or DSLR hardly at all. I defeated it by downloading a software which lets me convert videos into particular files. So, I