我制作了两个网格并使用嵌套面板将它们添加到窗口中。唯一的问题是我无法在中心移动网格,也无法在各自的网格下获取标签。尝试使用 setBounds 但这不起作用。有什么建议吗?我添加了当前状态的图像。我想分别在第一个和第二个网格下显示玩家和对手标签。
public static void main(String[] args) {
window = new JFrame();
window.setTitle("Battleship.exe");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setPreferredSize(new Dimension(800, 800));
P1_container = new JPanel(new GridLayout(10,10));
P1_container.setPreferredSize(new Dimension(400, 400));
P1_container.setBorder(BorderFactory.createLineBorder(Color.black, 5));
compContainer = new JPanel(new GridLayout(10,10));
compContainer.setPreferredSize(new Dimension(400, 400));
compContainer.setBorder(BorderFactory.createLineBorder(Color.black, 5));
grid = new JPanel[10][10];
for (int i =0; i< 10; i++) {
for (int j =0; j< 10; j++) {
grid[i][j] = new JPanel();
grid[i][j].setBackground(Color.white);
grid[i][j].setBorder(BorderFactory.createLineBorder(Color.blue, 2));
grid[i][j].setPreferredSize(new Dimension(35,35));
P1_container.add(grid[i][j]);
}
}
enemyGrid = new JPanel[10][10];
for (int i =0; i< 10; i++) {
for (int j =0; j< 10; j++) {
enemyGrid[i][j] = new JPanel();
enemyGrid[i][j].setBackground(Color.lightGray);
enemyGrid[i][j].setBorder(BorderFactory.createLineBorder(Color.red, 2));
enemyGrid[i][j].setPreferredSize(new Dimension(35, 35));
compContainer.add(enemyGrid[i][j]);
}
}
GridLayout layout = new GridLayout(1, 2);
layout.setHgap(150);
mainPanel = new JPanel(layout);
mainPanel.add(P1_container);
mainPanel.add(compContainer);
player = new JLabel("PLAYER");
player.setBounds(100, 410, 5, 5);
opponent = new JLabel("OPPONENT");
opponent.setBounds(100, 410, 5, 5);
panel = new JPanel();
panel.setPreferredSize(new Dimension(100, 100));
panel.add(mainPanel, BorderLayout.CENTER);
panel.add(player, BorderLayout.WEST);
panel.add(opponent, BorderLayout.WEST);
window.add(panel, BorderLayout.CENTER);
window.pack();
window.setVisible(true);
}