-1

I am having trouble getting an image to show up on my application. Can you see where I am going wrong? I just need the image to show up on the pane like everything else. The JPanel is named contentPane. Everything else shows up.

    books = new ImageIcon("books.png");
    imgLabel = new JLabel();
    imgLabel.setIcon(books);
    imgLabel.setBounds(300, 315, 203, 141);
    contentPane.add(imgLabel);
J. Schei
  • 327
  • 3
  • 15
paxtuik
  • 47
  • 1
  • 13
  • Hi, try to check the path of the books.png. Also add some text to the JLabel. At least you will see that that label is displaying correct then – Reg Jun 02 '16 at 21:34
  • nice call I changed it to "src/books.png" and it worked. I have another project where I have the image sitting in the src folder and just putting the name of the file in the ImageIcon worked. Any idea why it would work there but not here? – paxtuik Jun 02 '16 at 21:51
  • 1
    1) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). .. – Andrew Thompson Jun 03 '16 at 02:35
  • 2
    .. 2) Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An [tag:embedded-resource] must be accessed by URL rather than file. See the [info. page for embedded resource](http://stackoverflow.com/tags/embedded-resource/info) for how to form the URL. 3) Please search before asking. Both the preceding points are covered multiple times a day. – Andrew Thompson Jun 03 '16 at 02:36
  • Where is the image located relative to the class files? – MadProgrammer Jun 03 '16 at 05:31

1 Answers1

0

I copied and added your code to a JFrame and it ran without a problem.

See

 public static void main(String[] args) {
   JFrame jFrame = new JFrame();
   ImageIcon books = new ImageIcon("books.png");
   JLabel imgLabel = new JLabel("test");
   imgLabel.setIcon(books);
   imgLabel.setBounds(300, 315, 203, 141);
   jFrame.getContentPane().add(imgLabel);
   jFrame.setVisible(true);
 }

My suggestion would be to double check your books file path.

J. Schei
  • 327
  • 3
  • 15
Reg
  • 10,717
  • 6
  • 37
  • 54
  • nice call I changed it to "src/books.png" and it worked. I have another project where I have the image sitting in the src folder and just putting the name of the file in the ImageIcon worked. Any idea why it would work there but not here? – paxtuik Jun 02 '16 at 21:58
  • Place the image in the root of your project. That should solve it :) – Reg Jun 02 '16 at 22:00
  • this is such a common blah question -nobody answers these anymore - you could as well create a script and point these users to known answers – gpasch Jun 02 '16 at 22:49