Reputation: 3029
I'm using Dr. Java as a compiler for Java. I am trying to include an image inside my code. I'm building my first GUI program.
This is the code I used:
import java.awt.*;
import javax.swing.*;
public class Test{
public static void main(String[] args){
JFrame frame = new JFrame("Test Program");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel primary = new JPanel();
primary.setBackground(color.green);
primary.setPreferredSize(new Dimension(100,100));
JLabel label = new JLabel("Tesing the program");
primary.add(label);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
}
}
Lets say there's a file on my desktop called image.gif and I want to include this image in my code.
Upvotes: 2
Views: 16562
Reputation: 21
Or you could serialize a java.awt.image.BufferedImage under a class name and store it with the binaries in a resources folder, but why not simply properly structure your applications folders.
java.awt.Toolkit obtained from the swing or awt container is used to acquire images the java.awt.Graphics object is used paint images onto the container and is also obtained through a method on the gui container you wish to paint on.
Another more complex imaging file manipulation system is in core java api called javax.imageio
Upvotes: 1
Reputation: 604
Can I store images as variables to use them in my code?
yes you can. by using this command: ImageIcon image = new ImageIcon("C:\image.gif");
(instead of C:\image.gif you must write your image location)
Where is the image usually stored in a java program and how can I refer to it?
imageicon
helps you to show your image and put it where you want.
Is an image a form of object?
everything in java is an object, except primitive types.
What is the code to include the image I have in the program I am writing on Dr. Java?
first you must place your image somewhere you wanna refer to. and then define it as I told. and use how you want according the references.
Upvotes: 3
Reputation: 24626
Can I store images as variables to use them in my code?
Yes, images are usually stored as variables.
Where is the image usually stored in a java program and how can I refer to it?
Images, basically are termed as application resources, that are used to provide some information, apart from text displayed on the GUI
You can have a look at working with Images and this simple example
As you deploy an application, Images
used in the application are often embedded into the JAR
file, along with the rest of the application. This answer, might can give you more information, as to how to add a resource to the project
Upvotes: 1
Reputation: 324147
Im building my first GUI program.
Start by reading the Swing tutorial on Creating a GUI With Swing
for all the basics and lots of working examples.
I want to include this image in my code.
You can start with the section on How to Use Icons
.
Upvotes: 3