我試圖用秋千來構建一個井字游戲。使用網格布局會出現奇怪的行數和列數,并且似乎無法將其變為 3x3。我究竟做錯了什么?我應該只使用浮動布局并設定位置嗎?
import java.awt.*;
import javax.swing.*;
public class main {
public static void main(String[] args) {
JFrame frame = new JFrame("Tic Tac Toe");
JPanel panel = new JPanel();
frame.add(panel);
GridLayout grid = new GridLayout(3,3);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setLayout(grid);
frame.setResizable(false);
JButton button1 = new JButton();
JButton button2 = new JButton();
JButton button3 = new JButton();
JButton button4 = new JButton();
JButton button5 = new JButton();
JButton button6 = new JButton();
JButton button7 = new JButton();
JButton button8 = new JButton();
JButton button9 = new JButton();
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.add(button4);
frame.add(button5);
frame.add(button6);
frame.add(button7);
frame.add(button8);
frame.add(button9);
}
}
uj5u.com熱心網友回復:
首先,感謝@Abra 指出我沒有添加任何解釋,因為我有點匆忙寫答案。
首先執行以下步驟:
將布局分配給您的面板,如下所示: panel.setLayout(grid);
然后,將面板添加到您的框架中,如下所示: frame.add(panel);
然后,通過替換frame為panel添加按鈕的位置,將所有小部件添加到面板。
現在,您的 JFrame 出現了一些問題,因為您還向 Frame 添加了一個空的 JPanel。我讓您將 JPanel 添加到 JFrame 并將網格布局分配給面板,只是因為我認為井字游戲將包括游戲結果的顯示。因此,您可以簡單地使用 remove() 方法洗掉 JPanel 并添加結果 JPanel。
uj5u.com熱心網友回復:
雖然您已經接受了 @JustinCoding
解釋
Originally, in order to add components to a JFrame, you had to first call method getContentPane which returned a Container that you could add components to. JFrame is referred to as a top level container and its content pane is the container for all the components that you add to it. The default content pane is a JPanel whose layout manager is BorderLayout. Hence no need to add your components to a JPanel and add that JPanel to the JFrame. You can add components directly to the JFrame. Just be aware that when you are adding components directly to a JFrame, you are actually adding them to a JPanel with BorderLayout.
And since the content pane is a JPanel, you are free to also change its layout manager – as you have done in your code via this line:
frame.setLayout(grid);
Note that you only need to set one of the dimensions in the GridLayout constructor. Here is a quote from the javadoc of that constructor.
One, but not both, of rows and cols can be zero, which means that any number of objects can be placed in a row or in a column.
In other words, for your tic-tac-toe game, you need only set the columns to 3. That means that each row will contain no more than three columns so when you add nine buttons, GridLayout will ensure that they will be arranged in three rows of three columns each. Hence, for your tic-tac-toe board, you can use the following code.
GridLayout grid = new GridLayout(0, 3); // zero rows and three columns
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/331478.html
