import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.swing.*;
public class StackingCards {
private JPanel getContent(BufferedImage[] images) {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridwidth = GridBagConstraints.REMAINDER;
panel.add(new GraphicComponent(images), gbc);
panel.add(getZOrderComponent(images), gbc);
return panel;
}
private JPanel getZOrderComponent(BufferedImage[] images) {
JPanel panel = new JPanel(null);
Dimension d = new Dimension(300,100);
panel.setPreferredSize(d);
int iw = images[0].getWidth();
int ih = images[0].getHeight();
int overlap = iw/4;
int x0 = (d.width - iw - (images.length-1)*overlap)/2;
int y = (d.height - ih)/2;
for(int i = 0; i < images.length; i++) {
JLabel label = new JLabel(new ImageIcon(images[i]));
panel.add(label);
int x = x0 + i*overlap;
label.setBounds(x, y, iw, ih);
panel.setComponentZOrder(label, 0);
}
Component[] c = panel.getComponents();
for(int i = 0; i < c.length; i++) {
System.out.printf("c[%d] zOrder = %d%n",
i, panel.getComponentZOrder(c[i]));
}
return panel;
}
public static void main(String[] args) throws IOException {
String prefix = "images/geek/geek";
String[] ids = {
"-----", "-c---", "--g--", "---h-", "----t"
};
String ext = ".gif";
BufferedImage[] images = new BufferedImage[ids.length];
for(int i = 0; i < images.length; i++) {
String path = prefix + ids[i] + ext;
images[i] = javax.imageio.ImageIO.read(new File(path));
}
StackingCards test = new StackingCards();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(test.getContent(images));
f.pack();
f.setVisible(true);
}
}
class GraphicComponent extends JPanel {
BufferedImage[] images;
public GraphicComponent(BufferedImage[] images) {
this.images = images;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int w = getWidth();
int h = getHeight();
int iw = images[0].getWidth();
int ih = images[0].getHeight();
int overlap = iw/4;
int x0 = (w - iw - (images.length-1)*overlap)/2;
int y = (h - ih)/2;
for(int i = 0; i < images.length; i++) {
int x = x0 + i*overlap;
g.drawImage(images[i], x, y, this);
}
}
public Dimension getPreferredSize() {
return new Dimension(300,100);
}
} |