Como adiconar uma imagem em um jpanel

Bom eu fiz isso até o momento porém não está adicionando a img ao fundo do jpanel:

public class NewJFrame extends javax.swing.JFrame {
    ImageIcon fundo = new ImageIcon(getClass().getResource("C:\\My Mobile Projects\\EXPRESS_FTCPesquisa2\\bg.jpg"));
    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
        
    }
    
    public void paintComponent(Graphics g) { 
        super.paintComponents(g);
        Image img = fundo.getImage();
        g.drawImage(img, 0, 0, this);
 
    }

eu criei um jpanel dentro de um jfraem e dei o nome dele de bgLogin

Boa noite.
Cara, sugiro vc colocar um jLabel dentro desse jPanel. Fica mais fácil e melhor.

Aí vc adiciona a imagem no jLabel

jLabel.setIcon(new javax.swing.ImageIcon("C:\\Users\\Teste\\Pictures\\teste.png"));

Aí se quiser definir o tamanho | dimensão da imagem, vc pode usar os atributos com valores inteiros, EX:

jLabel.setBounds(x, x, x, x);
jLabel.setSize(X, X);

o único problema disso é que tenho que setar layout como nulo pq se não fica bugado quando adiciona um button, mesmo assim é melhor?

Há N jeitos de fazer isso, eu faço assim: deixo o layout como absoluto e quando termino, passo tudo para o design livre (que consigo deixar maximizado).

Você pode se basear nesse ImagePanel que fiz há alguns anos, se você setar setStretchEnabled(true) ele vai esticar a imagem, se fizer setStretchEnabled(false), ele vai desenhar ela lado à lado.

import java.awt.*;
import java.awt.image.*;

import javax.swing.*;

public class ImagePanel extends JPanel {

	private boolean stretchEnabled;

	private static final long serialVersionUID = 1;

	private BufferedImage image;

	public ImagePanel() {
		stretchEnabled = true;
	}

	public BufferedImage getImage() {
		return image;
	}

	public boolean isStretchEnabled() {
		return stretchEnabled;
	}

	public void setImage(BufferedImage image) {
		this.image = image;
	}

	public void setStretchEnabled(boolean stretch) {
		this.stretchEnabled = stretch;
	}

	@Override
	protected void paintComponent(Graphics g) {
		if (image == null) {
			super.paintComponent(g);
			return;
		}
		int w = getWidth();
		int h = getHeight();
		if (stretchEnabled) {
			g.drawImage(image, 0, 0, w, h, this);
			return;
		}
		int iw = image.getWidth();
		int ih = image.getHeight();
		int colunas = w / iw;
		int linhas = h / ih;
		if (colunas * iw < w) {
			colunas++;
		}
		if (linhas * ih < h) {
			linhas++;
		}
		int offsetX = 0;
		for (int i = 0; i < linhas; i++) {
			int y = i * ih;
			if (y > h) {
				break;
			}
			for (int j = 0; j < colunas; j++) {
				int x = j * iw + offsetX;
				if (j == 0 && x > 0) {
					g.drawImage(image, -(iw - x), y, iw, ih, this);
				}
				if (j == colunas - 1 && x < w) {
					g.drawImage(image, x + iw, y, iw, ih, this);
				}
				if (x > w) {
					break;
				}
				if (x < -iw) {
					break;
				}
				g.drawImage(image, x, y, iw, ih, this);
			}
		}
	}
}
2 curtidas