我正在尝试使用java swing进行10x10 board
。但我不知道为什么其中一个盒子不合适。我在99 grid
中设置了另一个setBounds()
,但最后一个网格位于0,0 position
。
我使用jButton
作为grid
。我做错了什么提示?
我写的代码到目前为止:
JFrame frame = new JFrame();
JButton[][] grid;
int y = 10;
int x = 10;
public Board() {
initComponents();
jButton = new JButton[x][y];
setGrid();
}
private javax.swing.JButton[][] jButton;
public void setGrid(){
int size = 75;
int o = size * x;
int p = size * y;
int k = 0;
int l = 0;
int z = 9;
for(int i=p;i>0;i-=size){
for(int j=0;j<o;j+=size){
jButton[k][l] = new javax.swing.JButton();
jButton[k][l].setBounds(j, i, size, size);
jButton[k][l].setBackground(Color.yellow);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton[k][l])
)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton[k][l])
));
if(k==9){
k=0;
}
else{
k++;
}
}l++;
}
}
public static void main(String[] args){
JFrame frame = new JFrame("Board");
frame.setContentPane(new Board());
Dimension dmsn = new Dimension();
dmsn.height = 1080;
dmsn.width = 1920;
Insets insets = frame.getInsets();
frame.setMinimumSize(dmsn);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
答案 0 :(得分:2)
for(int i=p;i>0;i-=size){
for(int j=0;j<o;j+=size){
jButton[k][l] = new javax.swing.JButton();
jButton[k][l].setBounds(j, i, size, size);
jButton[k][l].setBackground(Color.yellow);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
setLayout
代码放在循环之前。NULL
布局Container
设为网格时,请使用GridLayout
。GroupLayout
:使用它不是不可能,但是很乏味。