I cannot implement a image onto a GUI - java

I am using eclipse and I want to add a image onto a label or a logo for my GUI.
I want it to LOOK LIKE THIS!
I uploaded it onto the web because I dont have 10 reputation.
(Names cool program) is the image
import java.awt.*;
import javax.swing.*;
import javax.swing.JFrame;
public class MainClass extends JFrame{ // super class JFrame
// Kind of a tutorial for creating GUI's in java
private JLabel label;
private JLabel label1;
private JButton button;
private JTextField textfeild;
private ImageIcon image1; // image for my logo
public MainClass () {
setLayout (new FlowLayout());
image1 = new ImageIcon (getClass ().getResource ("logo.gif")); // declares image
label = new JLabel ("This is the label");
add (label);
label1 = new JLabel (image1); // adds image
add (label1);
textfeild = new JTextField (15);
add (textfeild);
button = new JButton ("Click");
add (button);
}
public static void main(String[] args) {
MainClass gui = new MainClass ();
gui.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); // creates window
gui.setSize (300,300);
gui.setVisible (true);
gui.pack ();
gui.setTitle ("Title");
}
}
Program compiles but doesn't run. Gives me
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at JonsCalc.<init>(JonsCalc.java:18)
at JonsCalc.main(JonsCalc.java:38)

This piece of code getClass().getResource ("logo.gif") means that the image should be loaded from the same location as your class MainClass has. Check that you image is in the same package as MainClass. If you use Eclipse, than put image file in the package in src folder, it will be copied to bin automatically.

I suggest you create a package exclusively for your images/icons, then create a single loader class there named 'ImageLoader' or whatever you want. You can then use this code...
new ImageLoader().getClass().getResource("NAME_OF_IMAGE"));

Right click on your class then go to new. Click on new Source Folder. Finally move your images in that folder. Now you can use that code.

If you are using Eclipse, copy your images to your package and your project's bin folder. Then just type
image1 = new ImageIcon(this.getClass().getResource("filename.filetype"));

Related

Set background in a JFrame

I waned to put a background in a JFrame, so I searched on YouTube and found a Video, but it didn't work I tried another one and this didn't work either so what is wrong with my code
because all the time i start it is just not there but eclipse dont mark anything wrong.
package Pack;
import javax.swing.*;
public class Gui {
public Gui(){
JLabel background;
Var.jf = new JFrame();
Var.jf.setSize(Var.screenwidth, Var.screenheight);
Var.jf.setTitle("test");
Var.jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Var.jf.setResizable(false);
Var.jf.setVisible(true);
Var.jf.setLocationRelativeTo(null);
Var.jf.setLayout(null);
ImageIcon img = new ImageIcon("Bilder/Testbild");
background = new JLabel("",img,JLabel.CENTER);
background.setBounds(0,0,1000,1000);
Var.jf.add(background);
Var.Buttonxstart = new JButton("Start");
Var.Buttonxstart.setBounds(300,220,400,120);
Var.jf.add(Var.Buttonxstart);
Var.Buttonxclose = new JButton("Exit");
Var.Buttonxclose.setBounds(300,440,400,120);
Var.jf.add(Var.Buttonxclose);
}
}
.
package Pack;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Var {
static JFrame jf;
static int screenheight = 1000;
static int screenwidth = 1000;
static JButton Buttonxstart;
static JButton Buttonxclose;
}
Some points:
code should check if the image is really being loaded - ImageIcon does not throw any Exception if the file is not found. Test if the height or width is -1 or not, example:
if (img.getIconHeigth() == -1) {
throw new FileNotFoundException("image: Bilder/Testbild");
}
or better IMO, use ImageIO.read().
the whole GUI code should run in the EDT (Event Dispatch Thread), see Swing's Threading Policy. . Unable to see if it is, if not, use some code like SwingUtilities.invokeLater(() -> new Gui());
3. it is not recommended to use the null layout manager.Check the Laying Out Components Within a Container tutorial.
Note: I tested the posted code - it's working, if calling new Gui() on the EDT and having an image Testbild in folder Bilder. But for background image I would prefer to override the paintComponent method of a JPanel, to paint the image.

Why is my Image Icon not showing up in my JFrame?

I am trying to display an image icon PNG, I have properly referred to the file called "logo.png" inside the project folder and set the icon as seen below. I'm not sure where I went wrong as I followed this tutorial starting around minute 14 (https://www.youtube.com/watch?v=Kmgo00avvEw&t=298s), I have made sure the code was correct but I'm still unable to get the image to appear beside the text when I run the code in Eclipse.
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.Rectangle;
import javax.swing.ImageIcon;
public class mainClass {
public static void main(String[] args) {
// JFrame is a GUI frame to add components to
//JLabel a GUI display area for a string of texts and image.
ImageIcon image = new ImageIcon("logo.png");
JLabel label = new JLabel(); //creates JLabel
label.setText("Welcome to Magic Shape"); //sets text for label
label.setIcon(image);
JFrame frame = new JFrame(); //creates JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //close operations when...
frame.setSize(500, 500); //sets size of JFrame (can resize)
frame.setTitle("Magic Shape"); //title of Program
frame.setVisible(true); //makes frame visible
frame.add(label); //adds label
}
}
package be.project.jframe;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.io.IOException;
import java.io.InputStream;
public class Main {
public static void main(String[] args) throws IOException {
// JFrame is a GUI frame to add components to
//JLabel a GUI display area for a string of texts and image.
InputStream stream = Main.class.getResourceAsStream("/be/project/jframe/icons/400.png");
ImageIcon icon = new ImageIcon(ImageIO.read(stream));
JLabel jLabelObject = new JLabel("Welcome to Magic Shape");
jLabelObject.setIcon(icon);
JFrame frame = new JFrame(); //creates JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //close operations when...
frame.setSize(800,600);
frame.setTitle("Magic Shape"); //title of Program
frame.setVisible(true); //makes frame visible
frame.add(jLabelObject); //adds label
frame.pack();
}
}
According to your code, Java searches for the file logo.png in the working directory. The working directory is the value returned by System.getProperty("user.dir"). If Java does not find the file, it essentially creates a null icon and that's why you aren't seeing the icon.
Just make sure you put the file in the correct directory.
Refer to the following.
Accessing Resources
Retrieving Resources
How to Use Icons
Make sure the png file is placed at current working directory:
System.out.println(System.getProperty("user.dir"));

Java cannot see jlabel in jframe nor imageIcon

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?

Background Image of a window in Java using JFrame

So, I've recently started learning Java, and I am really enjoying it despite the several issues and things that I have not yet understood, it makes me keep going on with it. So, considering that it is my first ever programming language, bear with me on any "noob" mistakes I make.
So, I created a fullscreen window using JFrame:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main extends JFrame {
public static void main(String[] args) {
//Window
JFrame mainWindow = new JFrame("Day One");
mainWindow.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainWindow.setUndecorated(true);
mainWindow.setVisible(true);
//End Window
}
}
And then I tried to add a background image to the window by adding this:
mainWindow.setLayout(new BorderLayout());
mainWindow.setContentPane(new JLabel(new ImageIcon("C:\\Users\\Recordings\\Desktop\\Day One\\Images\\Main-Background-Image.png")));
mainWindow.setLayout(new FlowLayout());
I found this code here but it isn't working at all. In this website there are two different ways of making it but I have tried both of them and none works.
I have also searched here, in stackoverflow, for similar questions, but all of them were either unanswered or answered with the same example as mine.
I really hope I have been clear enough, thank you very much for your time
EDIT:
As suggested, I have separated the long single statement:
mainWindow.setContentPane(new JLabel(new ImageIcon("C:\\Users\\Recordings\\Desktop\\Day One\\Images\\Main-Background-Image.png")));
Into three more easier debugged statements:
ImageIcon image = new ImageIcon("C:\\Users\\Recordings\\Desktop\\Day One\\Images\\Main-Background-Image.png");
JLabel label = new JLabel(image);
mainWindow.setContentPane(label);
Just a few tips
Its usually best to put a panfel within a frame and then add components to that. Makes for good containment when swing classes get a bit bigger.
Its better to create a resource folder for your projects. Create one in the source of your project e.g. where the src and bin folders are located for your project and name it "resources".
When creating and image icon its good practice to surround with a try catch so you can give appropriate errors and locate easily, or even handle the error at runtime.
With all that being said, here is your code with a little extra. It creates a panel to hold the jlabel(image) and it adds that panel to the frame. It creates an image icon with a quick method, all you have to do is pass in the file name. This method assumes you have created the folder in your project directory called resources and placed your image in there.
public static void main(String[] args) {
//Window
JFrame mainWindow = new JFrame("Day One");
mainWindow.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainWindow.setUndecorated(true);
//Create image
JLabel imageHolder = new JLabel();
imageHolder.setIcon(makeImageIcon("example.png"));
//Add image to panel, add panel to frame
JPanel panel = new JPanel();
panel.add(imageHolder);
mainWindow.add(panel);
mainWindow.setVisible(true);
}
//Creates imageicont from filename
public static ImageIcon makeImageIcon(String filename) {
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(new File("resources/" + filename));
} catch (IOException e) {
e.printStackTrace();
}
return new ImageIcon(myPicture);
}
Hope this helps

My code does not show images from frame

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Concentration extends JFrame implements ActionListener {
private JButton buttons[][]=new JButton[4][4];
int i,j,n;
public Concentration() {
super ("Concentration");
JFrame frame=new JFrame();
setSize(10000,10000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel=new JPanel(new GridLayout(4,4));
panel.setSize(4000, 4000);
for( i=0; i<buttons.length; i++){
for (j=0; j<buttons[i].length;j++){
n=i*buttons.length+buttons[i].length;
buttons[i][j]=new JButton(new ImageIcon("1.jpg"));
panel.add(buttons[i][j]);
}
}
add(panel);
pack();
setVisible(true);
}
public static void main(String args[]){
new Concentration();
}
}
I put the images in images folder in package folder but it doesnot show. What am i doing wrong?
I will make a memory game but still cant do anything. And should i use label instead of icon to show picture? Or jtogglebutton or jbutton?
If the image is internal (you want a location relative to your project, or perhaps packaged into your jar) :
new ImageIcon(getClass().getResource("/images/1.jpg"));
The path is relative, so path/ will be a folder in the same folder as your project (or packaged into your jar).
If you want an external image, simply hand ImageIcon constructor the path (ex. "C:/.../file.png"). This isn't recommended though, as it's better to use it as a resource.
For more info on the ImageIcon constructor, see here. for more info on loading class resources, see here (Javadoc links)

Categories

Resources