是否可以将一组图像作为gridlayout的“背景图像”,其他图像是gridlayout的“内容”?
如果没有,最好的方法是什么?
答案 0 :(得分:6)
是的,这当然是可能的。将一个作为保存GridLayout的JPanel的背景。这可以通过在JPanel的paintComponent方法中绘制图像来完成。如果您希望网格的单元格显示背景图像,请务必将其opaque属性设置为false。如果它们是JLabel,那么默认情况下已经完成了。
编辑:例如:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
@SuppressWarnings("serial")
public class OverLayImages extends JPanel {
public static final String BACKGROUND_URL = "http://duke.kenai.com/misc/Bullfight.jpg";
public static final String CELL_URL = "http://duke.kenai.com/iconSized/penduke-transparent.gif";
private static final int ROWS = 3;
private static final int COLS = 4;
private BufferedImage backgroundImage;
private BufferedImage cellImage;
public OverLayImages() throws MalformedURLException, IOException {
backgroundImage = ImageIO.read(new URL(BACKGROUND_URL));
cellImage = ImageIO.read(new URL(CELL_URL));
ImageIcon cellIcon = new ImageIcon(cellImage);
setBackground(Color.white);
setPreferredSize(new Dimension(backgroundImage.getWidth(), backgroundImage.getHeight()));
setLayout(new GridLayout(ROWS, COLS));
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
JLabel label = new JLabel(cellIcon);
add(label);
}
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (backgroundImage != null) {
g.drawImage(backgroundImage, 0, 0, null);
}
}
private static void createAndShowUI() {
JFrame frame = new JFrame("OverLayImages");
try {
frame.getContentPane().add(new OverLayImages());
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
答案 1 :(得分:4)