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
| public class AbsoluteImagePanel extends JPanel {
public AbsoluteImagePanel() {
super();
setLayout(null);
}
public void addImage(Image image, int x, int y, int width, int height) {
JLabel label = new JLabel(new ImageIcon(image));
label.setBounds(x, y, width, height);
add(label);
setComponentZOrder(label, 0); // pour que le dernier s'affiche au dessus
}
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final AbsoluteImagePanel panel = new AbsoluteImagePanel();
frame.getContentPane().add(panel);
final Random random = new Random();
final Image image = ImageIO.read(new File("suricate.png"));
for(int i=0; i<10; i++) {
addImage( panel, image, random );
}
panel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
addImage( panel , image, random );
panel.repaint();
}
});
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void addImage(AbsoluteImagePanel panel, Image image, Random random) {
int x = random.nextInt(200);
int y = random.nextInt(150);
int width = 10 + random.nextInt(90);
int height = 10 + random.nextInt(90);
panel.addImage(image, x, y, width, height);
}
} |
Partager