我正在尝试向两个JFrame添加一个按钮数组以形成一个网格,但是当我尝试这样做时,第一个JFrame没有按钮,但第二次添加按钮时所有按钮都在那里。
我的代码是
<form action="/signup" method="post">
<select name="make">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select name="model">
<option value="volvo">Volvo</option>
</select>
<input type="submit" value="Submit">
</form>
</html>
如何在两个不同的JFrame中显示相同的数组?
答案 0 :(得分:2)
答案 1 :(得分:2)
您需要有两组数组,每个JFrame一个。
组件的实例只能添加到一个容器中。在您的代码中,您将所有按钮放在第一个JFrame中,但是当您将它们添加到第二个JFrame时,您也将它们从第一个JFrame中删除。
答案 2 :(得分:2)
每个GUI组件只能包含一次。如果组件已经在容器中并且您尝试将其添加到另一个容器,则该组件将从第一个容器中删除,然后添加到第二个容器中。
因此,要解决您的问题,您需要创建两个单独的按钮数组;请记住,现在当一个玩家进行移动时,你必须将它应用于两个网格:
private static final int GRID_WIDTH = 8;
private static final int GRID_HEIGHT = 8;
JFrame whiteFrame = new JFrame();
JFrame blackFrame = new JFrame();
JPanel blackGrid = new JPanel();
JPanel whiteGrid = new JPanel();
JButton[][] whiteTiles = new JButton[GRID_WIDTH][GRID_HEIGHT];
JButton[][] blackTiles = new JButton[GRID_WIDTH][GRID_HEIGHT];
JButton whiteAIButton = new JButton();
JButton blackAIButton = new JButton();
JLabel whiteLabel = new JLabel();
JLabel blackLabel = new JLabel();
public GUI() {
populateArray(whiteTiles);
populateArray(blackTiles);
initGUI();
}
private void populateArray(JButton[][] btnArray) {
for (int x = 0; x < btnArray.length; x++) {
for (int y = 0; y < btnArray[0].length; y++) {
btnArray[x][y] = new JButton();
}
}
}
private void initGUI() {
whiteAIButton.setText("Greedy AI (play white)");
whiteLabel.setText("White Player - click place to put piece");
fillGrid(whiteGrid, whiteTiles);
whiteFrame.setLayout(new BorderLayout());
whiteFrame.setTitle("Reversi White Player");
whiteFrame.add(BorderLayout.NORTH, whiteLabel);
whiteFrame.add(BorderLayout.CENTER, whiteGrid);
whiteFrame.add(BorderLayout.SOUTH, whiteAIButton);
whiteFrame.pack();
whiteFrame.setVisible(true);
blackAIButton.setText("Greedy AI (play black)");
blackLabel.setText("Black player - not your turn");
fillGrid(blackGrid, blackTiles);
blackFrame.setTitle("Reversi Black Player");
blackFrame.setLayout(new BorderLayout());
blackFrame.add(BorderLayout.NORTH, BlackLabel);
blackFrame.add(BorderLayout.CENTER, blackGrid);
blackFrame.add(BorderLayout.SOUTH, blackAIButton);
blackFrame.pack();
blackFrame.setVisible(true);
}
private void fillGrid(JPanel grid, JButton[][] tiles) {
grid.setLayout(new GridLayout(GRID_WIDTH, GRID_HEIGHT));
for (int x = 0; x < GRID_WIDTH; x++) {
for (int y = 0; y < GRID_HEIGHT; y++) {
grid.add(tiles[x][y]);
}
}
}
注意:我将ReversiButton
更改为JButton
,以便代码可以自行编译。