Java Swing GUI

How to Set Background Image in Java Swing

In this tutorial, we are going to see how to set background image in Java Swing. In the following example we have used this image, you can upload it to your project.
 

How to Set Background Image in Java Swing

 

import javax.swing.*;
import java.awt.*;

public class ImageBackground 
{
  public static void main(String args[]) 
  {
    JFrame frame = new JFrame("Display an image in the background");
    final ImageIcon icon = new ImageIcon("background.png");
    JTextArea text = new JTextArea() 
    {
      Image img = icon.getImage();
      // instance initializer
      {setOpaque(false);}
      public void paintComponent(Graphics graphics) 
      {
        graphics.drawImage(img, 0, 0, this);
        super.paintComponent(graphics);
      }
    };
    JScrollPane pane = new JScrollPane(text);
    Container content = frame.getContentPane();
    content.add(pane, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(3);
    frame.setSize(400, 300);
    frame.setVisible(true);
  }
}

Output:


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *