put a
setContentPane(new JLabel(new ImageIcon("C:\\img_url")));
in your jframe constructor
Vra
I realise this question has been asked many times but I feel it has not been properly answered.
I want to use an image as a background in a java gui
I have tried the following:
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
public class worldGUI extends JFrame implements ActionListener
{
private ImageIcon world = new ImageIcon("C://Users/Hans/Documents/world/map.png");
private JLabel map = new JLabel(world);
private JButton borders = new JButton("Borders");
public worldGUI()
{
setTitle("Welcome to the World");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,500);
setLocation(100,100);
setVisible(true);
borders.addActionListener(this);
map.add(borders);
setVisible(true);
}
}
I'm new to java so please be patient with me
Oplossing 2
put a
setContentPane(new JLabel(new ImageIcon("C:\\img_url")));
in your jframe constructor
Ander wenke
This is an informative post, designed to highlight some of the shortcomings of using JLabel
as background container, there are plenty of good examples already on SO, go up-vote those
While using a JLabel
as container for a background is a common approach to the problem, there are a number of issues which need to be taken in consideration...
JLabel
will not resize the image to fit the available container size. Not a show stopper, but if your content exceeds the size of the background image, the image will not be resized to accommodate it.JLabel
does not have a layout manager by default. Not a show stopper, but you need to beware that you will need to supply oneLEFT
. Not a show stopper, but you should beware that you may need to adjust it's propertiesFor example, the following has (deliberately) been setup to allow the content to exceed the boundaries of the background image, which is displayed using a JLabel
and the content added to it.
Another, commonly used, solution, which overcomes these issues, is to use a JPanel
and paint the image your self.
You gain control over the ability to scale the image as required, you can better control the layout requirements and positioning of the image.
See How to set a background picture in JPanel and How do I resize images inside an application when the application window is resized? for examples