在我的BoardPanel类中,我添加了一个具有16x16 GridLayout的JPanel。该JPanel是在createGridPanel()
方法内部创建的,在那里我还用RotatableJLabel
填充了网格的单元格,这是JLabel的子类,它仅支持旋转。现在,当我运行该应用程序时,网格将显示一个额外的列(17),最后一行的最后几个单元格为空。我一直在检查代码,但看不到我在做什么错。据我所知,我正在填补所有牢房。我在这里想念什么?
public class BoardPanel extends JLayeredPane {
// Constructor
public BoardPanel() {
setPreferredSize(new Dimension(650,700)); // set the size of the JLayeredPane
// Create the necessary non-grid related components
JLabel logo = createLogo();
RedRectangularJLabel redHomeArea = new RedRectangularJLabel("Home",Color.red, Color.white,55,255);
RedRectangularJLabel redStartArea = new RedRectangularJLabel("Start",Color.red,Color.white,150,44);
YellowRectangularJLabel yellowHomeArea = new YellowRectangularJLabel("Home",Color.yellow,Color.white,495,360);
YellowRectangularJLabel yellowStartArea = new YellowRectangularJLabel("Start", Color.yellow,Color.white,400,572);
JPanel grid = createGridPanel();
// Add the components to the layered pane
add(grid,0);
add(redHomeArea,1);
add(redStartArea,1);
add(yellowHomeArea,1);
add(yellowStartArea,1);
add(redPawn1,2);
add(redPawn2,2);
add(yellowPawn1,2);
add(yellowPawn2,2);
add(logo,3);
// Move the non-grid components to the front of the layered pane to make them visible
moveToFront(logo);
moveToFront(redHomeArea);
moveToFront(redStartArea);
moveToFront(yellowHomeArea);
moveToFront(yellowStartArea);
moveToFront(redPawn1);
moveToFront(redPawn2);
moveToFront(yellowPawn1);
moveToFront(yellowPawn2);
}
/**
* Creates a JPanel with a 16x16 GridLayout
* and populates its cells with the appropriate data.
* @return The final JPanel with a populated 16x16 grid
*/
private JPanel createGridPanel() {
JPanel panel = new JPanel(new GridLayout(16,16));
panel.setPreferredSize(new Dimension(650,700));
panel.setBounds(0,0,650,700);
RotatableJLabel gridLabel;
for(int i =0; i < 256; i++) {
if(i == 5) gridLabel = new RotatableJLabel(blueSlideEnd,90);
else gridLabel = new RotatableJLabel();
panel.add(gridLabel,i);
}
return panel;
}
}
使用new GridLayout(0,16)
代替new GridLayout(16,16)
。
检查https://docs.oracle.com/javase/tutorial/uiswing/layout/grid.html了解更多详细信息。