如何填充两个面板之间的边框?

How can I fill in the border between two panels?

这是我的井字游戏基本模板:

package myProjects;

import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.event.*;

public class SecondTickTacToe extends JFrame{

public JPanel mainPanel;
public static JPanel[][] panel = new JPanel[3][3];

public static void main(String[] args) {
    new SecondTickTacToe();
}
public SecondTickTacToe(){
    this.setSize(310, 400);
    this.setTitle("Tic Tac Toe");
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);

    mainPanel = new JPanel();

    for(int row=0; row<3; row++){
        for(int column=0; column<3; column++){
            int top=0;
            int bottom=0;
            int left=0;
            int right=0;
            panel[row][column] = new JPanel();
            panel[row][column].addMouseListener(new Mouse());
            panel[row][column].setPreferredSize(new Dimension(90, 90));
            panel[row][column].setBackground(Color.GREEN);
            if(column==0||column==1)
                right = 5;
            if(column==1||column==2)
                left = 5;
            if(row==0||row==1)
                bottom = 5;
            if(row==1||row==2)
                top = 5;
            panel[row][column].setBorder(BorderFactory.createMatteBorder(top, left, bottom, right, Color.BLACK));
            addItem(panel[row][column], row, column);
        }
    }

    this.add(mainPanel);
    this.setVisible(true);
}
private void addItem(JComponent c, int x, int y){
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = x;
    gbc.gridy = y;
    gbc.weightx = 100.0;
    gbc.weighty = 100.0;
    gbc.fill = GridBagConstraints.NONE;
    mainPanel.add(c, gbc);
    }
}
class Mouse extends MouseAdapter{
public void mousePressed(MouseEvent e){
    if(e.getSource() instanceof JPanel)
        ((JPanel)e.getSource()).setBackground(Color.BLUE);
    }
}

(您必须 运行 该程序才能看到我在说什么)

所以这是我的问题: 有什么方法可以在 JPanel 的边界之间填充 space 吗?我希望它是坚实的。使面板更大似乎不起作用,使边框尺寸更大似乎也没有任何作用。有谁知道如何使这项工作? (我的最终目标是让边框看起来像一个实心的井字游戏模板)

mainPanel = new JPanel();

JPanel 的默认布局是 FlowLayout。默认情况下,FlowLayout 在所有组件之间留下 5 像素的间隙。如果你不想要这个差距,那么你需要改变布局。阅读 FlowLayout API,您会发现允许您指定 0 间隙的构造函数。

但是,使用 FlowLayout 可能不是最佳布局。 GridLayout 是更容易用于行和列的布局。我建议您阅读 How to Use Grid Layout 上的 Swing 教程部分以获取更多信息和示例。将不需要您的 addItem(...) 方法。当您使用正确的 row/columns 创建 GridLayout 时,组件将自动换行到新行,因此您只需将组件添加到面板即可。

mainPanel.add(c, gbc);

顺便说一句,除非面板实际使用 GridBagLayout,否则指定 GridBagConstraint 不会执行任何操作,而事实并非如此。