Java - 调用的 paintComponent 将被读取但不会在运行时实现

Java - called paintComponent will be read but not implemented during runtime

本质上,我正在尝试向 JPanel 网格矩阵添加一个圆(这是我的主要问题所在)。 当 运行 下面的代码时,一旦调用新的 OvalComponent class 将圆添加到网格中的 (1,1) 位置,就会读取 class,但是绘制组件功能刚刚被跳过。

package Exercises;

import javax.swing.*;
import java.awt.*;
import java.io.FileNotFoundException;

/**
 * Created by user on 4/1/2017.
 */
public class Mazes extends JPanel {

public static void main(String[] args) throws FileNotFoundException {
    Mazes maze = new Mazes();
}

public Mazes() throws FileNotFoundException{
    Boolean[][] maze = Exercise4.readMaze();
    int row = maze.length;

    JFrame f = new JFrame("Maze");
    f.setLayout(new GridLayout(row, row));

    JPanel[][] grid = new JPanel[row][row];
    for (int i = 0; i < row; i++)        {
        for (int j = 0; j < row; j++)                {
            grid[i][j] = new JPanel();
            grid[i][j].setOpaque(true);
            if ((i==1&&j==1) || (i==row-1 && j==row-1))
                grid[i][j].add(new OvalComponent());

            if (maze[i][j].equals(false)){
                grid[i][j].setBackground(Color.BLACK);}
            else grid[i][j].setBackground(Color.WHITE);
            f.add(grid[i][j]);
        }
    }

    //f.add(new JButton("Reset"), BorderLayout.SOUTH);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setVisible(true);
}
class OvalComponent extends JComponent {
   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      g.setColor(Color.BLUE);
      g.fillOval(4, 4, 10, 10);
 }
}

OvalComponent 没有可定义的大小(默认为 0x0),因此在添加组件时,它的大小为 0x0,Swing 足够聪明,可以知道它不需要画它。[=​​15=]

覆盖组件的 getPreferredSize 方法和 return 适当的大小

@Override
public Dimension getPreferredSize() {
    return new Dimension(18, 18);
}

举个例子