Domanda

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

È stato utile?

Soluzione 2

put a

setContentPane(new JLabel(new ImageIcon("C:\\img_url")));

in your jframe constructor

Altri suggerimenti

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...

  1. 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.
  2. JLabel does not have a layout manager by default. Not a show stopper, but you need to beware that you will need to supply one
  3. The default horizontal alignment of the label is LEFT. Not a show stopper, but you should beware that you may need to adjust it's properties
  4. The label will ignore the preferred size of its content. This is annoying, and relates to the first point. If your content exceeds the available size of the label's icon and text, the content may underflow or be reduced to it's minimum size requirements. This is especially annoying when you pack the frame...

For 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.

enter image description here

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top