我在使用 GridLayout 时遇到问题,并且整个 JPanel 没有被填充。我有一个 N * M Grid,我用 N * M Tiles 填充它(它们扩展了 JPanel)。添加所有这些图块后,JPanel 的底部和右侧仍有空间。我认为 GridLayout 应该填满整个 JPanel,并使其中的所有内容大小均匀?
编辑:我不想发布所有代码,因为有多个类。想也许有一个简单的解决方案。
public class MainFrame extends JFrame {
private static final long serialVersionUID = 3985493842977428355L;
private final int FRAME_HEIGHT = 800;
private final int FRAME_WIDTH = 700;
private MainPanel mainPanel;
public MainFrame() {
super("Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(FRAME_HEIGHT, FRAME_WIDTH);
setLocationRelativeTo(null);
mainPanel = new MainPanel();
getContentPane().add(mainPanel);
setVisible(true);
}
}
public class MainPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 3421071253693531472L;
private RoutePanel routePanel;
private ControlPanel controlPanel;
private GridBagConstraints gridBagConstraints;
private GridBagLayout gridBagLayout;
public MainPanel() {
routePanel = new RoutePanel();
controlPanel = new ControlPanel();
setBackground(Color.black);
gridBagLayout = new GridBagLayout();
setLayout(gridBagLayout);
gridBagConstraints = new GridBagConstraints();
createLayout();
}
private void createLayout() {
gridBagConstraints.weightx = 1;
gridBagConstraints.weighty = 1;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = GridBagConstraints.NORTH;
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagLayout.setConstraints(routePanel, gridBagConstraints);
add(routePanel);
gridBagConstraints.weightx = 1;
gridBagConstraints.weighty = .05;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = GridBagConstraints.SOUTH;
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagLayout.setConstraints(controlPanel, gridBagConstraints);
add(controlPanel);
}
}
public class RoutePanel extends JPanel{
/**
*
*/
private static final long serialVersionUID = 4366703088208967594L;
private final int GRID_ROWS = 30;
private final int GRID_COLS = 47;
public RoutePanel() {
setLayout(new GridLayout(GRID_ROWS, GRID_COLS, 0, 0));
for(int i = 0; i < GRID_ROWS * GRID_COLS; i++) {
add(new Tile());
}
setBackground(Color.orange);
}
}
public ControlPanel() {
}
public Tile() {
setBackground(Color.gray);
Border blackline;
blackline = BorderFactory.createLineBorder(Color.black);
setBorder(blackline);
}