嘿伙计们,所以我正在制作这个游戏井字游戏,并且想要知道如何在右边创建另一个列。你会在视觉上更好地理解:
这就是我现在所做的:
但如果我添加另一个按钮,它就会垂直向下。我怎么做它所以它横向到中间所以我可以做我的tic-tac-toe游戏。
代码:
import java.awt.Dimension;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import sun.org.mozilla.javascript.internal.xml.XMLLib.Factory;
public class TicTacToe {
JFrame frame;
JPanel contentPane;
JButton row1col1;
JButton row1col2;
JButton row1col3;
JButton row2col1;
JButton row2col2;
JButton row2col3;
JButton row3col1;
JButton row3col2;
JButton row3col3;
public TicTacToe() {
// TODO Auto-generated constructor stub
frame = new JFrame("Fds");
contentPane = new JPanel();
contentPane.setLayout(new BoxLayout(contentPane,BoxLayout.Y_AXIS));
contentPane.setBorder(BorderFactory.createEmptyBorder
(10, 10, 10, 10));
row1col1 = new JButton();
row1col1.setMargin( new Insets(10, 10, 10, 10) );
contentPane.add(row1col1);
row1col2 = new JButton();
row1col2.setMargin( new Insets(10, 10, 10, 10) );
contentPane.add(row1col2);
row1col3 = new JButton();
row1col3.setMargin( new Insets(10, 10, 10, 10) );
contentPane.add(row1col3);
row2col1 = new JButton();
row2col1.setMargin( new Insets(10, 10, 10, 10) );
contentPane.add(row2col1);
row2col2 = new JButton();
row2col2.setMargin( new Insets(10, 10, 10, 10) );
contentPane.add(row2col2);
row2col3 = new JButton();
row2col3.setMargin( new Insets(10, 10, 10, 10) );
contentPane.add(row2col3);
frame.setContentPane(contentPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private static void runGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
TicTacToe greeting = new TicTacToe();
}
public static void main(String[] args) {
/* Methods that create and show a GUI should be
run from an event-dispatching thread */
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
runGUI();
}
});
}
}
答案 0 :(得分:2)
所有关于你的布局:你已经指定了BoxLayout垂直放置控件。
只需使用另一个。您可以找到有关布局in the documentation
的更多信息GridLayout似乎对你的porpouse来说是完美的
答案 1 :(得分:2)
您需要使用GridLayout
代替BoxLayout
。
然后,网格布局管理器会将您的按钮放在网格状态中。
像这样(未经测试):
JButton[] grid = new JButton[9];
this.setLayout(new GridLayout(3,3,1,1));
for(int i = 0; i < 9; i++) {
JButton button = new JButton();
...//Attach event handlers, etc.
this.add(button);
grid.add(button);
}
上面的代码应创建一个3 x 3网格,并用按钮填充它。