Java comment afficher une image dans Jpanel

Résolu/Fermé
layeures Messages postés 286 Date d'inscription mercredi 13 juin 2007 Statut Membre Dernière intervention 22 juin 2018 - 23 sept. 2010 à 12:39
 geospatial - 14 mai 2012 à 23:15
Bonjour,
j ai essayer de faire un code qui affiche une image dans jpanel
mes je ni arrive pas pouvez vous m aidez a faire un code pour affichier une image dans un JPanel merci d'avance de votre

voici mon code

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewJFrame.java
 *
 * Created on 22 sept. 2010, 16:47:24
 */
import java.awt.Graphics;
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.*;

/**
 *
 * @author sofiene
 */
public class NewJFrame extends javax.swing.JFrame {

    /** Creates new form NewJFrame */
    public NewJFrame() {
        initComponents();
    panel = new panneau();
    getContentPane().add(panel);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        panel = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("jLabel1");

        javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
        panel.setLayout(panelLayout);
        panelLayout.setHorizontalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 334, Short.MAX_VALUE)
        );
        panelLayout.setVerticalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(29, 29, 29)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 418, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(82, 82, 82)
                        .addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(103, 103, 103)
                .addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(54, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

/*public void paintComponent (Graphics g){
                ImageIcon imIc = new ImageIcon("C:/Users/sofiene/Desktop/Lighthouse.jpg");
                Image im = imIc.getImage();
jPanel1.paintComponents(g);
g.drawImage(im, 10, 10, 10, 10, null);

}*/

class panneau extends JPanel {
ImageIcon image = new ImageIcon("C:/Users/sofiene/Pictures/kt_impact.gif");
public void paintComponent (Graphics g){
//                ImageIcon imIc = new ImageIcon("C:/Users/sofiene/Desktop/Lighthouse.jpg");
//                Image im = imIc.getImage();
panel.paintComponents(g);
g.drawImage(image.getImage(), 100, 100, 10, 10, panel);

}
}
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                NewJFrame frame = new NewJFrame();
                panel.setVisible(true);
//                jPanel1.paintComponents(Graphics JPanel);
  //              frame.paintComponents(jPanel1);

                //JLabel image = new JLabel( new ImageIcon( "mon_image.jpg"));
                //pane.setLayout(new BorderLayout, CENTER);

  /*              //frame.drawImage();
                jPanel1.checkImage(im, frame);
                jPanel1.setVisible(true);
*/
              //  jLabel1.setIcon(new ImageIcon("C:/Users/sofiene/Desktop/Lighthouse.jpg"));



                frame.setVisible(true);

            }
        });
    }

    // Variables declaration - do not modify
    private static javax.swing.JLabel jLabel1;
    private static javax.swing.JPanel panel;
    // End of variables declaration

}





A voir également:

8 réponses

varfendell Messages postés 3256 Date d'inscription jeudi 27 décembre 2007 Statut Membre Dernière intervention 8 février 2020 699
23 sept. 2010 à 14:34
Bonjour,

le code suivant affiche une image dans une fenetre:

import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
 
public class Panneau extends JPanel {
 
        public void paintComponent(Graphics g){
                try {
                        Image img = ImageIO.read(new File("nomImage.jpg"));
                        g.drawImage(img, 0, 0, this);
                        //Pour une image de fond
                        //g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                
        }               
}


à toi de t'en servir correctement
4
layeures Messages postés 286 Date d'inscription mercredi 13 juin 2007 Statut Membre Dernière intervention 22 juin 2018 3
23 sept. 2010 à 14:39
salut je te remercie de m'avoir donnee une solution
je vai de suis essayer ce code
et encore merci de m'avoir repondu
0
layeures Messages postés 286 Date d'inscription mercredi 13 juin 2007 Statut Membre Dernière intervention 22 juin 2018 3
23 sept. 2010 à 14:49
re salut j ai mis exatement le code que tu pas proposer est ca ne marche pas
quand je mes public pour la class panneau ca me detecte une erreur dans j ai enlever le public c est senser marcher mes ca ne marche pas
pouvez vous me dire ce qui ne va pas dans ce code
merci

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frame.java
 *
 * Created on 23 sept. 2010, 14:35:09
 */
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

/**
 *
 * @author sofiene
 */
public class frame extends javax.swing.JFrame {

    /** Creates new form frame */
    public frame() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        Panneau = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout PanneauLayout = new javax.swing.GroupLayout(Panneau);
        Panneau.setLayout(PanneauLayout);
        PanneauLayout.setHorizontalGroup(
            PanneauLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        PanneauLayout.setVerticalGroup(
            PanneauLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(64, 64, 64)
                .addComponent(Panneau, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(236, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(48, 48, 48)
                .addComponent(Panneau, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(152, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frame().setVisible(true);

            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JPanel Panneau;
    // End of variables declaration

}

class Panneau extends JPanel {

        public void paintComponent(Graphics g){
                try {
                        Image img = ImageIO.read(new File("C:/Users/sofiene/Desktop/Lighthouse.jpg"));
                        g.drawImage(img, 0, 0, this);
                        //Pour une image de fond
                        //g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }

        }
}
0
varfendell Messages postés 3256 Date d'inscription jeudi 27 décembre 2007 Statut Membre Dernière intervention 8 février 2020 699
23 sept. 2010 à 15:53
....tu comprend ce que tu code?

Fait un test du code que je t'es donné a part ave'c sa propre méthope main...ce que tu as fait ne va pas du tout, faut pas te contenter de recopier betement ce que je t'ai donné, il faut l'adapter a ton code.

Si il y a des choses que tu ne comprend pas sur les conteneur, je te conseil de jeter un coup d'oeil à ce cours:

Java et la programmation événementielle
et plus particulierement la partie
Une histoire de conteneur
0
layeures Messages postés 286 Date d'inscription mercredi 13 juin 2007 Statut Membre Dernière intervention 22 juin 2018 3
23 sept. 2010 à 16:13
salut
c est vrai que je du mal a comprends c est normal je debute
peu tu me dire quel son les erreur que j ai faite et la raison pour laquelle le code ne fonctionne pas.
merci
0
varfendell Messages postés 3256 Date d'inscription jeudi 27 décembre 2007 Statut Membre Dernière intervention 8 février 2020 699
23 sept. 2010 à 16:20
regarde le nom de la classe, tu l'utilise partout au dessus sans avant meme qu'elle n'existe, il faut changer ça. Et puis ou l'initialise tu? ou la declares tu et la lance tu?
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
layeures Messages postés 286 Date d'inscription mercredi 13 juin 2007 Statut Membre Dernière intervention 22 juin 2018 3
23 sept. 2010 à 16:26
merci pour c est remarque je croie que je commence a comprendre
0
varfendell Messages postés 3256 Date d'inscription jeudi 27 décembre 2007 Statut Membre Dernière intervention 8 février 2020 699
23 sept. 2010 à 16:33
en gros ce que je t'ai donné, tu ne gardes que la méthode, ou es fonction utilisé, et tu les insere dans ton code la ou tu en as besoin. mais in ne faut pas insérer tout la classe d'un coup comme ça.

Sur ce moi je vais partir, je reviens demain à 9h. bonne chance :)
0
layeures Messages postés 286 Date d'inscription mercredi 13 juin 2007 Statut Membre Dernière intervention 22 juin 2018 3
23 sept. 2010 à 16:43
j ai mis la class panneau tout au debut 1 probleme de resolu
ensuite
j ai inisialise dans le constructeur de la frame la class panneau jpanel
de cette maniere panneau de = new panneau();
pui j ai mis de.setVisible(true);

mes ca ne marche pas

bizare
0
layeures Messages postés 286 Date d'inscription mercredi 13 juin 2007 Statut Membre Dernière intervention 22 juin 2018 3
23 sept. 2010 à 17:30
I LOVE YOU MON AMIE varfendell

MERCI MERCI MERCI
ERECA ca marche ouaiHHHHHHHHHHHHHHHHH

merci beaucoup de ton aide c est rare les personne qui prend la peine d aidez les autres
merci
0
varfendell Messages postés 3256 Date d'inscription jeudi 27 décembre 2007 Statut Membre Dernière intervention 8 février 2020 699
24 sept. 2010 à 09:05
et bien, une bonne chose de faite :)
0
Salut ce code fonctionne a merveille


import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;


/**
* @author Tu mettras ton nom
*
*/
public class ImageFond extends JFrame {
private Container c;
private JPanel imagePanel;
private String filePath;

public ImageFond(String filePath) {
super("Image de fond");
this.filePath = filePath;
initialize();
}

private void initialize() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
c = getContentPane();
imagePanel = new JPanel() {
public void paint(Graphics g) {
try {
BufferedImage image = ImageIO.read(new File(filePath));
g.drawImage(image, 0, 0, null);
} catch (IOException e) {
e.printStackTrace();
}
}
};
imagePanel.setPreferredSize(new Dimension(640, 480));
c.add(imagePanel);
}

public static void main(String[] args) {
String imagePath = "C:\\ichigofirstbankai.jpg";
ImageFond fond = new ImageFond(imagePath);
fond.pack();
fond.setVisible(true);
}
}
0