我正在尝试设计一个用于java的井字游戏的UI,但我不明白为什么他们在UI中排在第5行。我想要有四行,其中底部三行可用作Board的按钮tictactoe和top row将用作显示给用户的重要消息。我附上了代码和UI的快照。
//code
package TicTacToe;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TicTacToeUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
JPanel[] row = new JPanel[4];
JButton[] button = new JButton[9];
String[] buttonString = {" "," "," ",
" "," "," ",
" "," "," "};
Dimension displayDimension = new Dimension(290, 45);
Dimension regularDimension = new Dimension(90, 90);
JTextArea display = new JTextArea(2, 20);
Font font = new Font("Times new Roman", Font.BOLD, 14);
public TicTacToeUI(){
super("TicTacToe");
setDesign();
setSize(350, 500);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(5,5);
setLayout(grid);
FlowLayout f1 = new FlowLayout(FlowLayout.CENTER);
FlowLayout f2 = new FlowLayout(FlowLayout.CENTER,1,1);//gap in cells
for(int i = 0; i < 4; i++ )
row[i] = new JPanel();
row[0].setLayout(f1);
for(int i = 1; i < 4; i++)
row[i].setLayout(f2);
for(int i = 0; i < 9; i++) {
button[i] = new JButton();
button[i].setText(buttonString[i]);
button[i].setBackground(Color.black);
button[i].setFont(font);
button[i].addActionListener(this);
}
display.setFont(font);
display.setEditable(false);
display.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
display.setPreferredSize(displayDimension);
for(int i = 0; i < 9; i++)
button[i].setPreferredSize(regularDimension);
row[0].add(display);
add(row[0]);
for(int i=1,k=0;i<4&&k<9;i++){
for(int j=0;j<3;j++){
row[i].add(button[k]);
k++;
}
add(row[i]);
}
setVisible(true);
}
public final void setDesign() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e) {
}
}
public static void main(String[] args) {
TicTacToeUI obj = new TicTacToeUI();
}
@Override
public void actionPerformed(ActionEvent ae) {
// TODO Auto-generated method stub
int x,y;
if(ae.getSource()==button[0]){
x=0;
y=0;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[1]){
x=0;
y=1;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[2]){
x=0;
y=2;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[3]){
x=1;
y=0;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[4]){
x=1;
y=1;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[5]){
x=1;
y=2;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[6]){
x=2;
y=0;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[7]){
x=2;
y=1;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[8]){
x=2;
y=2;
display.setText("x = " + x + "y = " + y);
}
}
}
答案 0 :(得分:1)
好吧,我不确定我是否理解你的问题,因为你遇到的问题就在这一行:
GridLayout grid = new GridLayout(5,5);
我想要有4行,然后将其更改为:
GridLayout grid = new GridLayout(4,5);
希望它有所帮助。