Carlos Carrizales Carlos Carrizales - 6 months ago 23
Java Question

Set a png as interface background java

I'm trying to set a png file as a jframe form's background like this sw, so to do this, I just create the jframe form Test2 and call it with:

public static void main(String[] args) {
Test2 t2 = new Test2();
t2.setOpacity(0.55f);
t2.setVisible(true);
}


In the java class, Test2, set as undecorated, and set a image in a panel as a example, but I don't it there anymore, how can I set it as a background of all my panels/jframe form?

public Test2() {
setUndecorated(true);
initComponents();
Imagen imagen = new Imagen();
panel1.add(imagen);
panel1.repaint();
}


Imagen class:

public class Imagen extends JPanel{

public Imagen() {
this.setSize(905, 488); //se selecciona el tamaño del panel //[767, 481]
}

//Se crea un método cuyo parámetro debe ser un objeto Graphics
public void paint(Graphics grafico) {
Dimension height = getSize();

//Se selecciona la imagen que tenemos en el paquete de la //ruta del programa
ImageIcon Img = new ImageIcon(getClass().getResource("/images/reborn.png"));

//se dibuja la imagen que tenemos en el paquete Images //dentro de un panel
grafico.drawImage(Img.getImage(), 0, 0, height.width, height.height, null);

setOpaque(false);
super.paintComponent(grafico);
}
}

Answer

To set a background image to a component you could use the paintComponent of a container (like a JPanel), something like this:

public class BackgroundPane extends JPanel {

  private Image image;

  public BackgroundPane(Image image) {
    super();
    this.setOpaque(false);
    this.image = image;
  }

  @Override
  protected void paintComponent(Graphics grphcs) {
    super.paintComponent(grphcs);
    // Draw image in center of component
    grphcs.drawImage(image, getWidth() / 2 - image.getWidth(this) / 2,
                            getHeight() / 2 - image.getHeight(this) / 2, 
                            this);
  }

}

To use it, you could do something like this:

public static void main(String[] args) {
  SwingUtilities.invokeLater(() -> {

    JFrame frame = new JFrame();
    frame.setSize(640, 480);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Remove border of JFrame
    frame.setUndecorated(true);
    // Set location in center
    frame.setLocationRelativeTo(null);
    // Set a transparent background
    frame.setBackground(new Color(1.0f, 1.0f, 1.0f, 0f));

    BackgroundPane panel = null;
    try {
      panel = new BackgroundPane(Toolkit.getDefaultToolkit().getImage(new URL(
              "http://www.shiaupload.ir/images/77810787432153420049.png")));
      panel.setOpaque(false);
    } catch (MalformedURLException ex) {
      System.out.println(ex);
      return;
    }
    frame.add(panel);
    setUI(panel);

    frame.setVisible(true);
  });
}

setUI is just a method to write a simple user interface to test it. A final result could be something like this:

enter image description here