如何在使用GridLayout时删除不可见的边距?

时间:2018-02-11 17:43:08

标签: java swing jpanel layout-manager grid-layout

我直截了当地说,我正在创建一个JPanel矩阵,当我点击按钮时会生成该矩阵,因为它会将文本区域中存储的内容作为数据,然后将面板的布局设置为FlowLayout,进入面板我将父面板的颜色设置为黄色,只是为了查看面板的显示方式。直到这里一切都很好。它生成面板并将它们放在网格中。

我遇到的问题是,当我调整窗口大小时,我意识到整个面板没有填满。就好像形成了一种无形的边缘。这个边际是我想要消除的。

常规窗口有BorderLayout,用于输入要删除文本区域间距的数据。

以下是代码:

package maze;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Ventana_prueba{
    public static void main(String[] args) {
        hola h = new hola();
        h.setVisible(true);
        h.setSize(500,500);
        h.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
class hola extends JFrame{
    JPanel pizzarra;
    JButton botoniniciar;
    JPanel[][] laberinto_visual;
    JTextArea tamanioo;
    public hola(){
        JPanel panelbotones = new JPanel();
        panelbotones.setLayout(new FlowLayout());
        pizzarra = new JPanel();
        pizzarra.setBackground(Color.yellow);
        //getContentPane().setLayout(new BorderLayout());
        botoniniciar = new JButton("hola");
        tamanioo = new JTextArea("        ");
        panelbotones.add(botoniniciar);
        panelbotones.add(tamanioo);
        add(panelbotones, BorderLayout.NORTH);
        add(pizzarra, BorderLayout.CENTER);
        panelbotones.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
        botoniniciar.addActionListener(new ciao());

    }
    class ciao implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent ae) {
            //pizzarra.setLayout(new GridLayout(WIDTH, WIDTH));
            pizzarra.removeAll();
            int tamanio = (Integer.parseInt(tamanioo.getText())*2);
            pizzarra.setLayout(new GridLayout(tamanio+1, tamanio+1));
            laberinto_visual = new JPanel[tamanio+1][tamanio+1];
            for (int i = 0; i < tamanio+1; i++) {
                for (int j = 0; j < tamanio+1; j++) {
                    JPanel temp = new JPanel();
                    if((i+j)%2==0){
                        temp.setBackground(Color.BLACK);
                    }else{
                        temp.setBackground(Color.WHITE);
                    }
                    pizzarra.add(temp);
                    //laberinto_visual[i][j]=temp;
                }
            }
        pizzarra.updateUI();
        }

    }
}

1 个答案:

答案 0 :(得分:-2)

使用功能: - panel.setBounds(x,y,width,height);