JPanel 帮助 - 绘制矩形

JPanel help- Drawing rectangles

我是第一次使用图形,但我遇到了一个问题,即除了背景(标识为 Bcolor)之外什么也没有显示。我正在尝试使用带有颜色 Lcolor 的 fill(new Rectangle) 方法制作带有线条的网格。我 运行 调试器,似乎没有任何语法、运行 时间或逻辑错误。有任何解决这个问题的方法吗?谢谢!

    public static void drawWindow(int Lcolor, int lineSize, int cellSize, int Bcolor){
    Graphics g = createWindow(cellSize, Bcolor, lineSize).getGraphics();
    Graphics2D g2d = (Graphics2D)g;
    for(int i = 0; i <= (frameValues(cellSize, lineSize)[2]); i++){
        g2d.setColor(new Color(Lcolor, Lcolor, Lcolor));
        g2d.fill(new Rectangle(lineSize * i + cellSize * i, 0, lineSize, frameValues(cellSize, lineSize)[1]));
        //.drawLine(xpos,ypos,xsize,ysize)
    }//for loop
    for(int j = 0; j < (frameValues(cellSize, lineSize)[3]); j++){
        g2d.setColor(new Color(Lcolor, Lcolor, Lcolor));
        g2d.fill(new Rectangle(0, lineSize * j + cellSize * j, frameValues(cellSize, lineSize)[0], lineSize));
    }//for loop

}

这是 createWindow() 方法:

public static JPanel createWindow(int cellSize, int Bcolor, int lineSize){
    JFrame frame = new JFrame("Evolution Of Life");
    frame.setSize(new Dimension(frameValues(cellSize, lineSize)[0], frameValues(cellSize, lineSize)[1]));
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    //making it visible
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    //creating panel
    JPanel panel = new JPanel();
    frame.getContentPane().add(panel);
    panel.setBackground(new Color(Bcolor, Bcolor, Bcolor));
    return panel;
}


//If you need anymore information, I'll be happy to supply.

不要在 JPanel 上调用 getGraphics。如果要绘制到 JPanel,请重写它的 paintComponent 方法并使用传递给该方法的 Graphics 对象,如 tutorials 中所述。

JPanel panel = new JPanel(){

    @Override
    protected void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(...);
        g.fill(...);
    }
};
frame.add(panel);