Não consigo colocar imagem em JFrame

12 respostas
N

Estou tentando colocar uma imagem de fundo em um JFrame,mas não dá certo, alguém pode me informar qual o meu erro, por favor?
Ou me explicar como isso pode ser feito?
segue o que tenho tentado sem êxito:

public class Principal extends JFrame {

	private JPanel contentPane;
	private Image img = new ImageIcon("fundo.jpg").getImage();
	public Principal() 
	{
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 710, 505);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		

		
	}
	
	public void paint(Graphics g) 
	{ 
		super.paint(g); 
		int x = ( img.getWidth ( null ) ); 
		int y = ( img.getHeight ( null ) ); 
		Dimension d = getSize(); 
		g.drawImage(img, 0, 0, d.width, d.height, null); 
	} 
	
}

obrigado…

12 Respostas

N

Crie um JLabel e use o setIcon

(...)
JLabel label = new JLabel();
label.setIcon(/*digite o caminho aqui*/);
(...)
N

mas como ficariam os outros componentes?
em cima do label?
obrigado…

V

Use o JImagePanel, do projeto Towel. O link para o projeto está na minha assinatura.

Para colocar uma imagem no fundo de um JFrame, você teria que criar um painel e editar o método paintComponent para que ele pinte lá a imagem. O JImagePanel faz isso e te dá diversas outras opções quando a imagem e o tamanho do JFrame não batem.

N

Obrigado ViniGodoy, como poderia usar isso no JPanel?
eu fiz isso mas não funcionou:

public class Principal extends JFrame 
{

	private JPanel contentPane;
	private JPanel panel;
	private Image img = new ImageIcon("fundo.jpg").getImage();
	// obtendo as dimenções do monitor
	private final int ALTURA_DO_MONITOR = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode().getHeight();
	private final int LARGURA_DO_MONITOR = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode().getWidth();;

	
	public Principal() 
	{
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(0, 0, LARGURA_DO_MONITOR, ALTURA_DO_MONITOR);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new GridLayout(1, 1, 0, 0));
		panel = new JPanel();
		
	}
	
/*	public void paint(Graphics g) 
	{ 
		super.paint(g); 
		int x = ( img.getWidth ( null ) ); 
		int y = ( img.getHeight ( null ) ); 
		Dimension d = getSize(); 
		g.drawImage(img, 0, 0, d.width, d.height, null); 
	} */
	
	public void paintComponent(Graphics g) 
	{        
		panel.paintComponents(g);     
		g.drawImage(img, 0, 0, this);      
		getContentPane().add(panel);    
	}
}

pode me informar o que errei?
obrigado…

V

Cuidado, na implementação do paintComponent, vc chamou super.paintComponent[color=red]s[/color].

O mais correto seria assim:

public void paintComponent(Graphics g) { paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.drawImage(img, 0, 0, null); g2d.dispose(); }

De qualquer forma, baixe o componente do projeto towel, pois a implementação lá está bem mais completa:

N

Muito obrigado ViniGodoy…
Só mais uma dúvida…
Eu uso o windowbuilder, é possivel usar este JImageoanel pelo windowbuilder?
Obrigado…

V

Provavelmente sim. Eu comecei a usar o Window Builder muito recentemente (ontem, mais pra ser mais exato) então não sei te responder como.

N

muito obrigado pelas respostas.
eu vi que tem como adicionar um novo componente lá na paleta dele para JPanel, está dando uns paus aqui, rsrsr
mas vou tentar…
obrigado

N

CONSEGUIIIIIIIIIIIIIII…
ViniGodoy, consegui colocar o JImagePanel no windowBuilder…
1 - criei uma classe com o o fonte igual ao fonte que vc me passou e 2 baixei a biblioteca.


https://github.com/MarkyVasconcelos/Towel/blob/mas…wel/swing/img/JImagePanel.java

2 - fui na aba containers, direito do mouse deu a opção add compont.

3 - depois eu arrastei o meu JPanel recem criado para o meu JFrame.

assim:

public class Principal extends JFrame 
{
	private static final long serialVersionUID = 1L;
	private BufferedImage imagem = null;
	
	public Principal()
	{
		setBounds(100, 100, 681, 563);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		getContentPane().setLayout(new GridLayout(1, 0, 0, 0));
		
		
		try 
		{
			imagem = ImageIO.read(new File("C:\\desenvolve\\hrwms\\HRServiceClient\\HRServiceClient\\HRServiceClient\\src\\br\\com\\hrtech\\hrserviceclient\\view\\fundo.jpg"));
		} catch (IOException e) 
		{
			e.printStackTrace();
		}
		JImagePanel panelPrincipal = new JImagePanel(imagem);

		getContentPane().add(panelPrincipal);
	}

}

e o fonte do meu painel

public class JImagePanel extends JPanel 
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private LoopImage images;
	// private BufferedImage image = null;
	private FillType fillType = FillType.RESIZE;

	/**
	 * Creates a new panel with the given background image.
	 * 
	 * @param img
	 *            The background image.
	 */
	public JImagePanel(BufferedImage img) {
		System.out.println(img);
		 setImage(img);
		images = new LoopImage(0, img);
	}

	/**
	 * Creates a new panel with the given background images looping at each tick
	 * interval.
	 * 
	 * @param tick
	 *            the time between swap the image
	 * @param imgs
	 *            The background images.
	 */
	public JImagePanel(long tick, BufferedImage... imgs) {
		images = new LoopImage(tick, imgs);
		new Looper().start();
	}

	/**
	 * Creates a new panel with the given background image.
	 * 
	 * @param img
	 *            The background image.
	 * @throws IOException
	 *             , if the image file is not found.
	 */
	public JImagePanel(File imgSrc) throws IOException {
		this(ImageIO.read(imgSrc));
	}

	/**
	 * Default constructor, should be used only for sub-classes
	 */
	protected JImagePanel() 
	{
		System.out.println("sssssssss");
	}

	/**
	 * Creates a new panel with the given background image.
	 * 
	 * @param img
	 *            The background image.
	 * @throws IOException
	 *             , if the image file is not found.
	 */
	public JImagePanel(String fileName) throws IOException {
		this(new File(fileName));
	}

	/**
	 * Changes the image panel image.
	 * 
	 * @param img
	 *            The new image to set.
	 */
	public final void setImage(BufferedImage img) {
		if (img == null)
			throw new NullPointerException("Buffered image cannot be null!");

		this.images = new LoopImage(0, img);
		// this.image = img;
		invalidate();
	}

	/**
	 * Changes the image panel image.
	 * 
	 * @param img
	 *            The new image to set.
	 * @throws IOException
	 *             If the file does not exist or is invalid.
	 */
	public void setImage(File img) throws IOException {
		setImage(ImageIO.read(img));
	}

	/**
	 * Changes the image panel image.
	 * 
	 * @param img
	 *            The new image to set.
	 * @throws IOException
	 *             If the file does not exist or is invalid.
	 */
	public void setImage(String fileName) throws IOException {
		setImage(new File(fileName));
	}

	/**
	 * Returns the image associated with this image panel.
	 * 
	 * @return The associated image.
	 */
	public BufferedImage getImage() {
		return images.getCurrent();
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		Graphics2D g2d = (Graphics2D) g.create();
		fillType.drawImage(this, g2d, images.getCurrent());
		g2d.dispose();
	}

	/**
	 * Returns the way this image fills itself.
	 * 
	 * @return The fill type.
	 */
	public FillType getFillType() {
		return fillType;
	}

	/**
	 * Changes the fill type.
	 * 
	 * @param fillType
	 *            The new fill type
	 * @throws IllegalArgumentException
	 *             If the fill type is null.
	 */
	public void setFillType(FillType fillType) {
		if (fillType == null)
			throw new IllegalArgumentException("Invalid fill type!");

		this.fillType = fillType;
		invalidate();
	}

	public static enum FillType {
		/**
		 * Make the image size equal to the panel size, by resizing it.
		 */
		RESIZE {
			@Override
			public void drawImage(JPanel panel, Graphics2D g2d,
					BufferedImage image) {
				g2d.drawImage(image, 0, 0, panel.getWidth(), panel.getHeight(),
						null);
			}
		},

		/**
		 * Centers the image on the panel.
		 */
		CENTER {
			@Override
			public void drawImage(JPanel panel, Graphics2D g2d,
					BufferedImage image) {
				int left = (panel.getWidth() - image.getWidth()) / 2;
				int top = (panel.getHeight() - image.getHeight()) / 2;
				g2d.drawImage(image, left, top, null);
			}

		},
		/**
		 * Makes several copies of the image in the panel, putting them side by
		 * side.
		 */
		SIDE_BY_SIDE {
			@Override
			public void drawImage(JPanel panel, Graphics2D g2d,
					BufferedImage image) {
				Paint p = new TexturePaint(image, new Rectangle2D.Float(0, 0,
						image.getWidth(), image.getHeight()));
				g2d.setPaint(p);
				g2d.fillRect(0, 0, panel.getWidth(), panel.getHeight());
			}
		};

		public abstract void drawImage(JPanel panel, Graphics2D g2d,
				BufferedImage image);
	}

	private class Looper extends Thread {
		public Looper() {
			setDaemon(true);
		}

		public void run() {
			while (true) {
				repaint();
				try {
					sleep(images.tick);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

}

espero que ajude aos iniciantes como eu…
Obrigado ViniGodoy…

N

a alegria durou pouco, rsrsrs
alguém sabe porque o jar não funciona?
tema lgum ajuste ou algo desse tipo pra funcionar com o JImagePane?
obrigado

S

Você pode estudar este exemplo, achei na internet mas não lembro a fonte. Uma dica… existe muito material bom sobre java em inglês, esse é um…
gerei um jar deste e ele acha a imagem…

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class BackgroundImagePanelExample {

    // Set up contraints so that the user supplied component and the
    // background image label overlap and resize identically
    private static final GridBagConstraints gbc;
    static {
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.anchor = GridBagConstraints.NORTHWEST;
    }

    /**
     * Wraps a Swing JComponent in a background image. Simply invokes the overloded
     * variant with Top/Leading alignment for background image.
     *
     * @param component - to wrap in the a background image
     * @param backgroundIcon - the background image (Icon)
     * @return the wrapping JPanel
     */
    public static JPanel wrapInBackgroundImage(JComponent component,
            Icon backgroundIcon) {
        return wrapInBackgroundImage(
                component,
                backgroundIcon,
                JLabel.TOP,
                JLabel.LEADING);
    }

    /**
     * Wraps a Swing JComponent in a background image. The vertical and horizontal
     * alignment of background image can be specified using the alignment
     * contants from JLabel.
     *
     * @param component - to wrap in the a background image
     * @param backgroundIcon - the background image (Icon)
     * @param verticalAlignment - vertical alignment. See contants in JLabel.
     * @param horizontalAlignment - horizontal alignment. See contants in JLabel.
     * @return the wrapping JPanel
     */
    public static JPanel wrapInBackgroundImage(JComponent component,
            Icon backgroundIcon,
            int verticalAlignment,
            int horizontalAlignment) {

        // make the passed in swing component transparent
        component.setOpaque(false);

        // create wrapper JPanel
        JPanel backgroundPanel = new JPanel(new GridBagLayout());

        // add the passed in swing component first to ensure that it is in front
        backgroundPanel.add(component, gbc);

        // create a label to paint the background image
        JLabel backgroundImage = new JLabel(backgroundIcon);

        // set minimum and preferred sizes so that the size of the image
        // does not affect the layout size
        backgroundImage.setPreferredSize(new Dimension(1,1));
        backgroundImage.setMinimumSize(new Dimension(1,1));

        // align the image as specified.
        backgroundImage.setVerticalAlignment(verticalAlignment);
        backgroundImage.setHorizontalAlignment(horizontalAlignment);

        // add the background label
        backgroundPanel.add(backgroundImage, gbc);

        // return the wrapper
        return backgroundPanel;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Background Image Panel Example");

        // Create some GUI
        JPanel foregroundPanel = new JPanel(new BorderLayout(10, 10));
        foregroundPanel.setBorder(
                BorderFactory.createEmptyBorder(10,10,10,10));
        foregroundPanel.setOpaque(false);

        foregroundPanel.add(new JLabel("Comment:"), BorderLayout.NORTH);
        foregroundPanel.add(new JScrollPane(new JTextArea(5,30)),
                BorderLayout.CENTER);
        foregroundPanel.add(
                new JLabel(
                "Please enter your comments in text box above." +
                " HTML syntax is allowed."), BorderLayout.SOUTH);

        frame.setContentPane(wrapInBackgroundImage(foregroundPanel,
                new ImageIcon(
                BackgroundImagePanelExample.class.getResource("/imagens/imagem.jpg"))));

        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}
M

A solução, que usei e funciona, inclusive no jar, se encontra no link:
https://netbeans.org/kb/docs/java/gui-image-display_pt_BR.html

Vá direto no item “Exibindo a imagem como Plano de Fundo no Quadro” do tutorial. Se tiver dificuldades, sigiro fazer todo tutorial. Eu fiz tudo pra pegar o jeito.

Espero ajudar…

Criado 8 de agosto de 2011
Ultima resposta 29 de ago. de 2013
Respostas 12
Participantes 5