简体   繁体   中英

Adding ImageIcon to JTabbedPane

I am attempting to add a picture to the first tab of a JTabbedPane, here is my code:

JTabbedPane application = new JTabbedApplication();
JPanel welcomePanel = new JPanel();
JLabel imageLabel = new JLabel(new ImageIcon("track.jpg"));
welcomePanel.add(imageLabel);
application.addTab("WELCOME", welcomePanel);
application.setMnemonicAt(0, KeyEvent.VK_1);

The image file is located in the same location as the class this code is in. For some reason, however, my image is not appearing. I have used the same JLabel and used text instead of an image and it appears. Can someone give me some insight into this problem?

Java doesn't know that the image is located directly beside the running class file. You have to hand in the absolute path. Which means Path + filename.

This little piece of code will help you to tell Java that the image is in the current working directory.

String file = new File("track.jpg").getAbsolutePath();

Added to your code snipped it looks like this:

JTabbedPane application = new JTabbedPane();
JPanel welcomePanel = new JPanel();
String file = new File("track.jpg").getAbsolutePath();

JLabel imageLabel = new JLabel(new ImageIcon(file));
welcomePanel.add(imageLabel);
application.addTab("WELCOME", welcomePanel);

The image file is located in the same location as the class this code is in

Instead of JLabel imageLabel = new JLabel(new ImageIcon("track.jpg")); which is looking for a file in the current working directory, you should be using Class#getResource which will return a URL to the embedded resource.

It's important to note, that resources which are store within the application context (ie embedded inside the Jar or within the source packages) aren't accessible as "files" anymore.

Instead, you could try using something like...

ImageIcon icon = new ImageIcon(ImageIO.read(getClass().getResource("track.jpg"));

to load the image. Unlike ImageIcon , ImageIO.read will throw an IOException if the image can't be read, which is always more useful than the silence that you get from ImageIcon

If this fails to work, more context on the structure of your app will be needed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM