Java cannot see jlabel in jframe nor imageIcon - java

I'm writing a simple Java code that shows a text inside a frame and substitutes the standard ImageIcon with a custom one (.png file), stored in the same directory of this Java file.
However, whenever I run the code no text appears inside the frame and I also noticed that no Image is shown as Icon.
I'm running Java on VsCode and the code is as follows:
public class Example{
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(420,420);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon image = new ImageIcon("icon.png");
frame.setIconImage(image.getImage());
Jlabel label = new Label();
label.setText("Hello there!");
frame.setVisible(true);
}
}
Needless to say that I'm importing javax.swing.ImageIcon, javax.swing.JFrame and javax.swing.JLabel.
Whenever I run the above code this is the frame that appears:
May this be a problem due to Virtualization not being set on on my computer?

Related

How do I import an image in intellij (JAVA)

I'm fairly new to coding and was trying to make a simple GUI with JAVA Swing. I wanted to place an image in a label but for some reason does the image does not show when I run the Code. Are there some requirements I don't know of or did I do something wrong?
package Part2Lables;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
//Label = a GUI display area for a string of text, an image, or both
ImageIcon image = new ImageIcon("Kakashi.png");
JLabel label = new JLabel(); // create a label
label.setText("This is text in a label"); // set text to the label
label.setIcon(image);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
frame.add(label);
}
}
This is the code I used (I did use imports but they are not visible in the pic.)

My icon image doesnt show up in JFrame on mac

My image for logo doesnt show up on mac. there is no java logo in Jframe to begin with?
what am I missing?
package test;
import javax.swing.*;
public class Demo {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("this is the frame title");
frame.setSize(420,420);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
ImageIcon image = new ImageIcon("logo.png");
frame.setIconImage(image.getImage());
}
}
the mac OS will not show your icon, there's nothing wrong with your code, what you can do is enable the look and feel for cross platform. here at the docs you can see how achieve this and configure it. Basically before start your jframe do this:
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName();
// you can even set a theme on it
MetalLookAndFeel.setCurrentTheme(new OceanTheme()); // since Metal is the L&F for cross platforms.
JFrame.setDefaultLookAndFeelDecorated(true);

Displaying icon on menu bar in Java Swing

I have an application with a Swing GUI and I would like to add a search-field with a search-button (lupe icon) to the menu bar. However, the lupe icon won't display. Here is my code:
public class Ui_Frame {
public static void main(String[] args) {
SwingUtilities.invokeLater(Ui_Frame::createAndShowGUI);
}
private static void createAndShowGUI() {
f = new JFrame("Myframe");
...
JMenuBar menubar = new JMenuBar();
Icon lupeIcon = new ImageIcon("Resources/lupe_icon.png");
JButton j_searchButton = new JButton(lupeIcon);
menubar.add(j_searchButton);
...
f.setJMenuBar(menubar);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
My project structure is like
Project
Src
Ui_Frame.java
Resources
lupe_icon.png
The resulting button shows no icon at all :
I do not get any error message, it compiles without problems. Even when I try to catch any exception from the new ImageIcon(...) I'm not getting any hint at what the error is.
Any ideas as to what Im doing wrong here?
EDIT:
Here is a minimal example:
import javax.swing.*;
public class test {
private static JFrame f;
public static void main(String[] args) {
SwingUtilities.invokeLater(test::createAndShowGUI);
}
private static void createAndShowGUI() {
f = new JFrame("Test");
JMenuBar menubar = new JMenuBar();
Icon lupeIcon = new ImageIcon(test.class.getResource("/Resources/lupe_icon.png"));
JButton j_searchButton = new JButton(lupeIcon);
menubar.add(j_searchButton);
f.setJMenuBar(menubar);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setSize(500,500);
f.setVisible(true);
}
}
As you can see I am now loading the image with class.getResource(...) as was suggested by #AndrewThompson and #SergiyMedvynskyy, but that does not solve the problem. Also I was told that my classes should not be static, but since my Main needs to be static for me to be able to run the program and I have been told that I should start the UI with SwingUtilities.invokeLater(test::createAndShowGUI);
which also forces createAndShowGUI() to be static, I do not know how to make it not static.
For me it's working without mention folder "Resources" in the path,
like that:
Icon lupeIcon = new ImageIcon(test.class.getResource("/lupe_icon.png"));
But, i'm not sure your project structure is correct.
If still doesn't work, try rename folder with small 'r', and maybe also change project structure, this is my structure:
\src\main\java... (all java files)
\src\main\resources (resources folder, it displayed for me like a package)
Note - i think best is to check why u can't get the image in debug
After switching to Icon lupeIcon = new ImageIcon(test.class.getResource("Resources/lupe_icon.png")); to load the icon instead of new ImageIcon("Resources/lupe_icon.png"); I noticed that I was getting nullpointer-exceptions, despite the image clearly being there. After some googling I found out that the resource folder apparently is not just any folder but has to be marked as the resource root folder, as suggested here.
After marking the folder everything works fine :)

Dynamically Add Image To JLabel [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am attempting to dynamically add an image to my JLabel then add the JLabel to my panel. My code is throwing no errors, but the image is never shown.
public JFrameGamePlay(String playername, String playerselected) {
initComponents();
playerimage = "/Users/owner/Downloads/__Pikachu.png";
ImageIcon pimage = new ImageIcon(playerimage);
JLabel lblPlayer = new JLabel(pimage);
pnlPlayer.add(lblPlayer);
pnlPlayer.validate();
pnlPlayer.repaint();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JFrameGamePlay().setVisible(true);
}
});
}
EDIT
So from further googling I came up with this syntax
JLabel lblPlayer;
lblPlayer = new JLabel(new ImageIcon(getClass().getClassLoader().getResource("__Image1.png")));
pnlPlayer.add(lblPlayer);
pnlPlayer.validate();
pnlPlayer.repaint();
but when I run the code I get this debug error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:217)
This is the GUI layout of how I want my data to appear - it is 1 panel on the left and 1 panel on the right - each with a label dynamically created and populated with an image. But no image is being populated.
EDIT 2
I added a black border around my 2 Panels, and when the JForm is loaded neither panel is being displayed. So it seems that what everyone is telling me that GUI designing in NetBeans is pretty buggy. How can I dynamically in my code behind add the two panels one left and one right with a size of 143, 246?
EDIT 3
Still no mustard and I'm using this syntax:
public JFrameGamePlay() {
initComponents();
JPanel leftpanel = new JPanel();
JPanel rightpanel = new JPanel();
JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftpanel, rightpanel);
JLabel lblPlayer = new JLabel(new ImageIcon("/resources/__Image1.png"));
leftpanel.add(lblPlayer);
leftpanel.validate();
leftpanel.repaint();
}
Use ImageIO.read(File) to read the Image. Like,
File playerimage = new File("/Users/owner/Downloads/__Pikachu.png");
ImageIcon pimage = new ImageIcon(ImageIO.read(playerimage));
JLabel lblPlayer = new JLabel(pimage);
pnlPlayer.add(lblPlayer);
The NullPointerException comes from the getResource("__Image1.png") returning null because it didn't find the file. You should prefix it with the location from the classpath (after all, the ClassLoader loads the file). E.g. if the image is in a res directory in your jar (or in your classpath):
JFrameGamePlay.class.getClassLoader().getResource("/res/__Image1.png")));
Or you can directly give a complete path:
new JLabel(new ImageIcon("/images/thewall.png"));
Example:
public class JFrameGamePlay extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 450, 300);
JPanel contentPane = new JPanel(new BorderLayout());
frame.setContentPane(contentPane);
JLabel label = new JLabel(new ImageIcon("/images/thewall.png"));
contentPane.add(label, BorderLayout.CENTER);
JLabel label1 = new JLabel(new ImageIcon(JFrameGamePlay.class.getResource("/javax/swing/plaf/basic/icons/JavaCup16.png")));
contentPane.add(label1, BorderLayout.NORTH);
frame.setVisible(true);
}
}
My code is throwing no errors, but the image is never added.
Yes, this is unfortunately how ImageIcon works. It doesn't throw exceptions or anything if it's unable to read from the filename or URL you pass to it. The code runs without error but simply shows nothing.
playerimage = "/Users/owner/Downloads/__Pikachu.png";
If you want to read from a file at a fixed location like this, then it won't be helpful to mess with getClassLoader().getResource(). That could be helpful to read an image file that you package with your application, but not to read an image in the user's home directory. Your original new ImageIcon(imageLocation) approach is appropriate for that.
[note: I think it's a good idea to send the filename (or URL) directly to the ImageIcon, as your original code does. Other answers suggest ImageIO.read(), which can be helpful to see where it's going wrong, but you could change it back to ImageIcon(filenameOrUrl) once you get it working. But it's not a big deal.]
I am attempting to dynamically add an image to my JLabel then add the JLabel to my panel.
If by "dynamically" you mean to do this when some event occurs, after the panel is already visible on the screen, then I suggest not doing that.
That is, instead of doing this...
JLabel lblPlayer = new JLabel(pimage);
pnlPlayer.add(lblPlayer);
pnlPlayer.validate();
pnlPlayer.repaint();
...you could add the JLabel to your panel (invisible because no text or image) at the very start, before your panel is shown on screen. Then dynamically add the ImageIcon to the already-extant JLabel. All you need to call is existingLabel.setIcon(...). There would be no need to call validate() or repaint().

swing doesn't show png icons on jbuttons

I have written a simple JFrame in java and added a button.
Then I added a .png icon to the button but it keeps giving me an exception.
(I don't have any problem with .jpg icons and it works well)
Here are my code and the exceptions.
public class Test
{
static JFrame mainFrame;
public static void main(String[] args)
{
mainFrame = new JFrame("a");
mainFrame.setSize(300, 300);
mainFrame.setLocation(50, 50);
JButton btn = new JButton();
ImageIcon icon = new ImageIcon("C:\\a.png");
btn.setIcon(icon);
btn.setSize(100, 100);
btn.setLocation(50, 50);
mainFrame.add(btn);
mainFrame.setVisible(true);
}
}
Exceptions :
sun.awt.image.PNGImageDecoder$PNGException: Broken file
at sun.awt.image.PNGImageDecoder.pngassert(PNGImageDecoder.java:94)
at sun.awt.image.PNGImageDecoder.handleChunk(PNGImageDecoder.java:107)
at sun.awt.image.PNGImageDecoder.getData(PNGImageDecoder.java:726)
at sun.awt.image.PNGImageDecoder.produceImage(PNGImageDecoder.java:252)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:269)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:205)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:169)
sun.awt.image.PNGImageDecoder$PNGException: Broken file
at sun.awt.image.PNGImageDecoder.pngassert(PNGImageDecoder.java:94)
at sun.awt.image.PNGImageDecoder.handleChunk(PNGImageDecoder.java:107)
at sun.awt.image.PNGImageDecoder.getData(PNGImageDecoder.java:726)
at sun.awt.image.PNGImageDecoder.produceImage(PNGImageDecoder.java:252)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:269)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:205)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:169)
Code is fine, there's problem with your image file

Categories

Resources