Domanda

I'm working on java to implement an window that contain an image as a background.

here is the code i made

import java.awt.*;
import javax.swing.*;
public class FenImage extends JFrame {

private JLabel question ;
private JButton valider ;
private JPanel pan ;


public FenImage()
{
    this.setTitle("Image");
    this.setBounds(200, 500,600,450);
    this.setLayout(new BorderLayout());
    JLabel question = new JLabel(" \t \t L'image qu'on peux utiliser pour présenter ce mot est : ");
    //this.add(question);
    this.getContentPane().add(question,BorderLayout.NORTH);
   JPanel pan = new JPanel()
    {
        protected void paintComponent(Graphics g) 
        {
            super.paintComponent(g);

            ImageIcon m = new ImageIcon("1.jpg");
            Image monImage = m.getImage();
            g.drawImage(monImage, 0, 0,this);

        }
    };
   this.getContentPane().add(pan);

but when i run i get only the label i added .

what's the problem ? and how can i add it correctly

È stato utile?

Soluzione

Add the label to the panel instead of the frame

JLabel question = new JLabel(" \t \t L'image qu'on peux utiliser pour présenter ce mot est : ");
JPanel pan = new JPanel()
{
        protected void paintComponent(Graphics g) 
        {
            super.paintComponent(g);

            ImageIcon m = new ImageIcon("1.jpg");
            Image monImage = m.getImage();
            g.drawImage(monImage, 0, 0,this);

        }
};
pane.setLayout(new BorderLayout());
pane.add(question, BorderLayout.NORTH);
this.getContentPane().add(pan);

You should avoid loading resources within the paint methods as this can increase your memory usage a slow your painting

Updated

ImageIcon(String) assumes that the String value is reference to a file on the file system. Contents stored in your src directory will be will be built into your jar, which turns it into embedded resources.

In order to load these resources, you need to use Class#getResource, for example

ImageIcon m = new ImageIcon(getClass().getResource("/1.jpg"));

This assumes the resource is in the default directory (top level directory) of your src directory

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top