+ Reply to Thread
Results 1 to 2 of 2

Thread: Add an image to a JButton

  1. #1
    Junior Member
    Join Date
    Jun 2012
    Posts
    14

    Add an image to a JButton

    I am trying to add an image to a JButton and I'm not sure what I'm missing. When I run the following code the button looks exactly the same as if I had created it without any image attribute. Water.bmp is in the root of my project folder.

    ImageIcon water = new ImageIcon("water.bmp");
    JButton button = new JButton(water);
    frame.add(button);

  2. #2
    Junior Member
    Join Date
    Jun 2012
    Posts
    14
    I think that your problem is in the location of the image. You shall place it in your source, and then use it like this:

    Code:
      JButton button = new JButton();
      try {
        Image img = ImageIO.read(getClass().getResource("resources/water.bmp"));
        button.setIcon(new ImageIcon(img));
      } catch (IOException ex) {
      }
    In this example, it is assumed that image is in src/resources/ folder.

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts