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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| public class DemoDrawImg extends JPanel {
private final static Image image1;
private final static Image image2;
private final static TexturePaint bg;
static {
image1 = readImage("vangogh.jpg");
image2 = readImage("cezanne.jpg");
BufferedImage bgimage = readImage("bg.jpg");
bg = bgimage==null?null:new TexturePaint(bgimage, new Rectangle(0,0,45,45));
}
private boolean drawImage2=false;
public DemoDrawImg() {
}
public void toggleImage() {
drawImage2=!drawImage2;
repaint();
}
@Override
public void paint(Graphics g) {
Graphics2D gr = (Graphics2D) g;
Dimension size = getSize();
gr.setPaint(bg);
g.fillRect(0, 0, (int)size.getWidth(), (int)size.getHeight());
gr.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
double width = size.width;
double height = size.height;
Image image=drawImage2?image1:image2;
double imgwidth=image.getWidth(this);
double imgheight=image.getHeight(this);
double coef = Math.min(width/imgwidth,height/imgheight);
coef/=1.5;
imgwidth*=coef;
imgheight*=coef;
gr.drawImage(image, (int)(size.width-imgwidth)/2, (int)(size.height-imgheight)/2, (int)(imgwidth), (int)(imgheight), this);
}
public static void main(String[] args) {
if (image1==null || image2==null || bg==null ) {
System.err.println("Erreur: image non trouvée");
return;
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(Toolkit.getDefaultToolkit().getScreenSize());
frame.setLocationRelativeTo(null);
final DemoDrawImg panel = new DemoDrawImg();
frame.getContentPane().add(panel);
frame.addWindowListener(new WindowAdapter() {
private Thread thread;
public void windowOpened(WindowEvent e) {
thread = new Thread() {
public void run() {
do {
try {
sleep(1000);
panel.toggleImage();
} catch (InterruptedException e) {
}
} while (!interrupted());
}
};
thread.start();
}
@Override
public void windowClosed(WindowEvent e) {
thread.interrupt();
}
});
frame.setVisible(true);
}
private static BufferedImage readImage(String filename) {
try {
return ImageIO.read(DemoDrawImg.class.getResource(filename));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
} |
Partager