1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| package project;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Train extends JPanel{
private BufferedImage image;
public Train() {
try {
image=ImageIO.read(getClass().getResourceAsStream("/train.jpg"));
}
catch(IOException e) {
e.printStackTrace();
}
showInFrame("My image", this);
}
public void paint(Graphics g) {
super.paint(g); // toujours appeler le super pour avoir le fond du composant/always call super to draw component background
g.drawImage(image, 100, 100, null, null); // tu devrais appeler g.drawImage(image,100,100,this), car si tu n'utilises pas de couleur, autant utiliser la signature qui ne l'utilise pas, et pour le paramètre observateur, utilises le panel lui-même, ce qui permettra un rafraîchissement automatique en cas de chargement progressif ou de gif animé / you should invoke g.drawImage(image,100,100,this) as if you don't need color, don't use signature with this argument, and you can use the panel itself at observer (if the image loading is progressive, or an animated gif, it will be refreshed automatically)
}
public static JFrame showInFrame(String title, JComponent component) {
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(component); // ajout du composant au centre de la fenêtre, add component at center
frame.setSize(600,400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
return frame;
}
public static void main(String[] args) {
Train t=new Train();
}
} |