一种选择是创建一个类,该类将表示将图像划分为网格的面板.唯一的问题是左上象限,它通常包含嵌套面板,在某些时候你希望它只包含一个空白面板.所以也许这样的事情(除了各种优化):
class GridPanel extends JPanel{
JLabel mountain, map, animal;
public GridPanel(JPanel panel){
super();
setLayout(new GridLayout(2, 2));
animal = new JLabel(new ImageIcon(getClass().getResource("pictures/animal.gif")));
map = new JLabel(new ImageIcon(getClass().getResource("pictures/map.gif")));
mountain = new JLabel(new ImageIcon(getClass().getResource("pictures/mountain.gif")));
add(panel);
add(mountain);
add(map);
add(animal);
}
}
请注意,它接受要在网格左上角显示的面板.然后使用指定的面板调用此coud.所以在你想要创建主面板的时候:
JPanel grid = new GridPanel(new JPanel()); //initial
for(int i = 1; i <= 5; i++){
grid = new GridPanel(grid);
}