0

So I've been playing around with JButtons and I've been trying to add an ImageIcon to a JButton. I have the following code:

window = new JFrame("Test");
window.setSize(1000, 600);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(null);

Icon icon = new ImageIcon("/Apple.jpg");
JButton apple = new JButton(icon);
apple.setBounds(50, 50, 200, 200);
window.add(apple);

I was wondering where would the Apple.jpg file have to be located for the code to work? Currently, Apple.jpg is located in the same package as this class.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Read the first answer to Different ways of loading a file as an InputStream https://stackoverflow.com/questions/676250/different-ways-of-loading-a-file-as-an-inputstream/676273#676273 – Gilbert Le Blanc Apr 03 '20 at 16:07
  • 1) 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. 2) 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. .. – Andrew Thompson Apr 27 '20 at 10:54
  • .. 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). 3) Don't set a window visible until all components are added and `pack()` is called. – Andrew Thompson Apr 27 '20 at 10:55

1 Answers1

0

Looking at the source code for constructor ImageIcon(String), leads me to the conclusion that the string you pass is treated as is.

Hence, according to the code you posted in your question, i.e.

Icon icon = new ImageIcon("/Apple.jpg");

Java will search for file Apple.jpg in the root directory.

If you are running on a Windows machine, like I am, Java considers my root directory to be C:\ (on my machine) so it will search for this file: C:\Apple.jpg

The answer linked to in this comment to your question (from Gilbert le Blanc) details all the different ways to load an image. I just tried to answer your question. So using the code in your question, the answer to it is that you would have to place your file (Apple.jpg) in the root directory. I'm assuming that you know where that is on your computer. In any case, I couldn't find enough information in your question to help you with that. for example, I couldn't tell what platform you are on.

Abra
  • 19,142
  • 7
  • 29
  • 41