2016-04-24 40 views
0

我试着做一个17 17网格布局板,但是当我运行代码,我产生被搞砸了,看起来像这样,而不是17 17按键板的板:按钮没有完全加载在网格布局

enter image description here

所以我的问题是为什么董事会显示这样怪异的,我如何得到它显示17 17按钮板,我想要的?

这里是我使用的代码:

public class TheJFrame { 
public static final char[][] board = new char[17][17]; 
public static class TheJFramez { 
    JFrame boardz = new JFrame("Game of Life"); 
    JPanel panel = new JPanel(); 
    public TheJFramez(){ 
     int r = 0,c; 
     boardz.setLayout(new GridLayout(board.length,board[r].length,1,1)); 
     for(r=0;r<board.length;r++){ 
      for(c = 0;c<board[r].length;c++){ 
       JButton tats = new JButton(" " + board[r][c] + " "); 
       panel.add(tats); 

      } 
     } 
     boardz.add(panel); 
     boardz.setVisible(true); 
     boardz.setSize(1200, 700); 
     boardz.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
    } 
} 
public static void main(String[] args) { 
    new TheJFramez(); 
} 
} 

回答

2

在这段代码中,您已设置“boardz”到网格布局的布局,而你所添加的按钮“面板”谁的布局没有规定这样,它将采用默认布局,当您将面板添加到“boardz”时,面板将以网格布局排列,而“面板”的组件仍然处于默认布局。

所以,你想添加JButton到boardz,没有使用面板。

下面是正确的代码: -

import java.awt.*; 
import javax.swing.*; 
public class TheJFrame { 
public static final char[][] board = new char[17][17]; 
public static class TheJFramez { 
    JFrame boardz = new JFrame("Game of Life"); 
    JPanel panel = new JPanel(); 
    public TheJFramez(){ 
     int r = 0,c; 
     boardz.setLayout(new GridLayout(board.length,board[r].length)); 
     for(r=0;r<17;r++){ 
      for(c = 0;c<17;c++){ 
       JButton tats = new JButton(" " + board[r][c] + " "); 
       boardz.add(tats); 
       System.out.print(board[r][c]); 
      } 
      System.out.println(); 
     } 

     boardz.setVisible(true); 
     boardz.setSize(1200, 700); 
     boardz.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
    } 
} 
public static void main(String[] args) { 
    new TheJFramez(); 
} 
} 

enter image description here

1

shubham你是正确的,但框取默认布局是FlowLayout中。因此,它们以线性方式排列,因此您可以将布局设置为网格布局。