将更多GridLayouted面板彼此相邻

时间:2013-11-29 13:40:08

标签: java swing

我正在使用3 JPanels生成一个棋盘,其中包含以下GridLayout s:

  1. 8x8 for gameboard
  2. 1x8用于从棋盘上留下的垂直标记
  3. 8x1用于电路板下的水平标记
  4. 我正在使用可调整大小的JFrame来完全包含它。我实际使用了this code,稍加修改。

    这意味着,在填充三个面板后,将它们添加到主JFrames面板,如下所示:

    Container contentPanel = getContentPane();
    /**Create some panels**/
    JPAnel 8x8 = new JPanel();
    8x8.setLayout(new GridLayout(8, 8));
    JPAnel 1x8 = new JPanel();
    8x8.setLayout(new GridLayout(1, 8));
    JPAnel 8x1 = new JPanel();
    8x8.setLayout(new GridLayout(8, 1));
    /**Populate frames**/
    ...
    /**Assign frames**/
    
    contentPanel.add(8x8, BorderLayout.CENTER);
    contentPanel.add(8x1, BorderLayout.SOUTH);
    contentPanel.add(1x8, BorderLayout.WEST);
    

    这并不是那么糟糕,但它看起来仍然如此:

    enter image description here

    底线扩展到垂直线。窗口越大,这个问题就越明显。

    我想将标记线粘贴到棋盘上,这样每个数字都会与适当的线对齐。

    我尝试将2x2布局分配给父框架contentPanel但是,网格布局似乎要求所有元素都具有相同的大小,因此它只会为8x1和{{1}创建更大的区域}。
    我的方法:

    1x8

    但结果更糟: enter image description here

    那我如何使用那些醉酒的网格布局呢? 或者我应该以不同的方式开始?

    修改 使用contentPanel.setLayout(new GridLayout(2, 2)); contentPanel.add(1x8); //vertical markers first contentPanel.add(8x8); //Then the chessboard //Create empty placeholder for bottom-right corner JPanel empty = new JPanel(); contentPanel.add(empty); //finally add bottom markers contentPanel.add(2x1);

    gridBaglayout

    结果:enter image description here

    稍微玩了一下后:

     contentPanel.setLayout(new GridBagLayout());
     /**Follows as after contentPanel.setLayout(new GridLayout(2, 2)); in the prewious code**/
    

    它不会尝试适合窗口:

    enter image description here

3 个答案:

答案 0 :(得分:4)

您可以使用9x9网格进行条件检查。这将使事情变得更简单和更好。使用条件检查可能生成此类布局可能如下:

GridLayout layout = new GridLayout(0,9);
        jPanel1.setLayout(layout);

        for(int row =0; row < 9; row++)
            for(int col=0; col<9;col++)
            {
                 JButton button = new JButton(); 
                if(col==0 && row==8)
                {    button.setEnabled(false);
                     button.setContentAreaFilled(false);
                }
                else if(col==0)
                    button.setText(""+(char)('A'+row));
                else if(row == 8)
                   button.setText(""+(char)('A'+col - 1)); 
                else if(col%2==0)
                    button.setBackground(Color.white);
                else     button.setBackground(Color.black);

                jPanel1.add(button);
            }

它的输出如下:

enter image description here

答案 1 :(得分:0)

也将gridBagLayout设为contentPane。这会将您的面板放置在所需的位置。 enter image description here

enter image description here

答案 2 :(得分:0)

要么使用9x9的一个面板(数字会与每个字段一样大)或使用GridBagLayout,这将为您提供完全控制。也就是说,GridBagLayout是一个完整的PITA。也许TableLayout更符合您的喜好。

相关问题