Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set an image as a background for Frame in Swing GUI of java?

Tags:

java

swing

I have created one GUI using Swing of Java. I have to now set one sample.jpeg image as a background to the frame on which I have put my components.How to do that ?

like image 292
om. Avatar asked Sep 23 '09 14:09

om.


People also ask

How do I change the background of a frame in Java?

In general, to set the JFrame background color, just call the JFrame setBackground method, like this: jframe. setBackground(Color. RED);


2 Answers

Perhaps the easiest way would be to add an image, scale it, and set it to the JFrame/JPanel (in my case JPanel) but remember to "add" it to the container only after you've added the other children components. enter image description here

    ImageIcon background=new ImageIcon("D:\\FeedbackSystem\\src\\images\\background.jpg");
    Image img=background.getImage();
    Image temp=img.getScaledInstance(500,600,Image.SCALE_SMOOTH);
    background=new ImageIcon(temp);
    JLabel back=new JLabel(background);
    back.setLayout(null);
    back.setBounds(0,0,500,600);
like image 143
Ankit Sharma Avatar answered Oct 08 '22 09:10

Ankit Sharma


There is no concept of a "background image" in a JPanel, so one would have to write their own way to implement such a feature.

One way to achieve this would be to override the paintComponent method to draw a background image on each time the JPanel is refreshed.

For example, one would subclass a JPanel, and add a field to hold the background image, and override the paintComponent method:

public class JPanelWithBackground extends JPanel {

  private Image backgroundImage;

  // Some code to initialize the background image.
  // Here, we use the constructor to load the image. This
  // can vary depending on the use case of the panel.
  public JPanelWithBackground(String fileName) throws IOException {
    backgroundImage = ImageIO.read(new File(fileName));
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Draw the background image.
    g.drawImage(backgroundImage, 0, 0, this);
  }
}

(Above code has not been tested.)

The following code could be used to add the JPanelWithBackground into a JFrame:

JFrame f = new JFrame();
f.getContentPane().add(new JPanelWithBackground("sample.jpeg"));

In this example, the ImageIO.read(File) method was used to read in the external JPEG file.

like image 43
coobird Avatar answered Oct 08 '22 07:10

coobird