JPanel帮助 - 绘制矩形

时间:2015-06-05 20:15:25

标签: java jframe jpanel

我第一次使用Graphics,但我遇到的问题是除了背景之外没有任何东西出现(标识为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.

1 个答案:

答案 0 :(得分:1)

请勿在{{1​​}}上致电getGraphics。如果您想要绘制到JPanel,请覆盖它的JPanel方法,并使用paintComponent中传递给该方法的Graphics对象,如tutorials中所述。

JPanel panel = new JPanel(){

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