JFrame setBackground

7 respostas
afdestro

olhei alguns post aqui do guj mas não consegui fazer funcionar…
como que eu faço para colocar como fundo do meu JFrame uma imagem?
de um modo facil de preferencia… para que eu possa mudar o fundo em tempo de execução tbm…

7 Respostas

_Renatu

isso deve funcionar:

(achei com uma pesquisa rapida no google)

http://forum.java.sun.com/thread.jspa?threadID=599393&messageID=3196643

Ironlynx

afdestro, adicione essa imagem a um desktoppane, nunca falha:

desktop = new JDesktopPane(){ Image im = (new ImageIcon("background.jpg")).getImage(); public void paintComponent(Graphics g){ g.drawImage(im,0,0,this); } };//fim do JDesktopPane contentPane.setOpaque(true); contentPane.add(desktop);//adiciono o JDesktopPane ao JPanel
contentPane é um JPanel adicionado ao seu JFrame.
Se for para mudar em tempo de execução dará um pouco maisde trabalho, provavelmente tendo que usar um Timer e sobescrevendo o método paintConponent.

afdestro

o complicado é fazer isso em tempod eexecução…
pelo visto não tem um jeito facil ;/

fabiofalci

Olha o exemplo abaixo, especialmente no metodo paintComponent.

Cada vez que muda o tamanho da tela, faço um resize na figura para este novo tamanho e pinto ele na tela.
Se tu olhar, eh uma nova imagem, com tamanho diferente, ou seja, esta mudando em tempo de execucao.

package panel;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyPanel extends JPanel {

    private Image image;

    public MyPanel() {
        this.initialize();
    }

    protected void initialize() {
        this.image = this.getImage("background.gif");
        
        this.setLayout(new BorderLayout());
    }

    public Image getImage(String path) {
        URL imageURL = getClass().getResource(path);
        if (imageURL == null)
            return null;

        return new ImageIcon(imageURL).getImage();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Dimension dDesktop = this.getSize();

        double width = dDesktop.getWidth();
        double height = dDesktop.getHeight();

        Image background = new ImageIcon(this.image.getScaledInstance(
                (int) width, (int) height, 1)).getImage();

        g.drawImage(background, 0, 0, this);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new MyPanel());
        frame.setSize(400, 300);
        frame.setVisible(true);
    }
}
afdestro

fabiofalci

estou no trabalho e não tem como testar…
esse seu exemplo é com JPanel… ele funciona com JFrame?
e se eu quizer mudar a imagem… é só chamar o metodo paintComponent? da onde eu pego esse parametro Graphics?

fabiofalci

Cara.
Te aconselho a sempre usar JPanel. Depois tu soh ‘cola’ esse teu JPanel no JFrame.
Assim quando tu quiser rodar em outro ‘Top-Level Container’ fica mais facil.

Sobre mudar a image. Tu nao chama diretamente paintComponent. e sim o java quando precisar desenhar de novo a tela.

Olha de novo esse exemplo, a cada 2s muda o figura de fundo e pinta novamente a tela.

package panel;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class MyPanel extends JPanel implements ActionListener {

	private Image image;

	private Image current;

	public MyPanel() {
		this.initialize();
	}

	protected void initialize() {
		this.image = this.getImage("background.gif");
		this.updateUI();

		this.setLayout(new BorderLayout());
		Timer t = new Timer(2000, this);
		t.start();
	}

	public Image getImage(String path) {
		URL imageURL = getClass().getResource(path);
		if (imageURL == null)
			return null;

		return new ImageIcon(imageURL).getImage();
	}

	public void actionPerformed(ActionEvent e) {
		if (this.current == null) {
			this.current = this.image;
		} else {
			this.current = null;
		}
		this.repaint();
	}

	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		if (this.current != null) {
			Dimension dDesktop = this.getSize();

			double width = dDesktop.getWidth();
			double height = dDesktop.getHeight();

			Image background = new ImageIcon(this.current.getScaledInstance(
					(int) width, (int) height, 1)).getImage();

			g.drawImage(background, 0, 0, this);
		}
	}

	public static void main(String[] args) {
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setContentPane(new MyPanel());
		frame.setSize(400, 300);
		frame.setVisible(true);
	}
}
afdestro

putz…
bem que poderia ter um
setBackground(Image img)
;/

Criado 29 de janeiro de 2007
Ultima resposta 30 de jan. de 2007
Respostas 7
Participantes 4