Adding image to my simple window
Hi,
I have made a simple window using the following code:
Code :
import java.awt.*;
import javax.swing.*;
class CreateWindow{
public static void main(String[]args){
//creating the window
JFrame frame = new JFrame("My Window");
//make the program terminate when the window is closed
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
//set the window location
frame.setLocationRelativeTo(null);
//set the window size
frame.setSize(400,200);
//create a JLabel object (a graphical component)
JLabel label = new JLabel("Hello");
//get ahold of the windows content pane and add the graphical component to it
frame.getContentPane().add(label);
//set the window to visible
frame.setVisible(true);
}
}
Could you tell the simplest way to getting an image displayed in my window. I assumed I would add an image to the JLabel object, but I dont know how to do this.
Re: Adding image to my simple window
Create an ImageIcon from the Image, make a JLabel from the ImageIcon, then add that JLabel to the GUI. See the following:
How to Use Icons (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)
Re: Adding image to my simple window
Thanks, do you know of a good tutorial which shows how to make the icon move on screen when a key is pressed.
Re: Adding image to my simple window
You might wish to read the following:
How to Use Swing Timers (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)
Lesson: Working with Images (The Java™ Tutorials > 2D Graphics)
Use the timer to change the icon position, then repaint. You might consider overriding paintComponent here rather than using an ImageIcon as it would give you more control over the position. Read the image using ImageIO, the draw using Graphics.drawImage within the paintComponent.
Re: Adding image to my simple window
Re: Adding image to my simple window
Quote:
Originally Posted by
TP-Oreilly
Thanks for the links.
You are welcome. Links such as this can readily be found with a little effort using a search engine and careful choice of keywords...I'm just saying.... ;)
Re: Adding image to my simple window
haha, i know, i have come across most of the links people have provided for me on here. I like to ask on here because people on here sometimes provide easy to understand explanations, without tooooo much technical jargon :)