用矩形创建网格

时间:2018-12-10 20:09:22

标签: java graphics grid rectangles

我正在尝试创建一个矩形网格,但不确定如何从这里开始? 我也不知道到目前为止是否正确

public CGOL (int x, int y, int size, int squares1) {
  numberOfSquares = 100;
  isAlive = new boolean [numberOfSquares][numberOfSquares];
  squares = new Rectangle.Double [numberOfSquares][numberOfSquares];
  int rows = 12;
  int cols = 40;
  int width = getSize().width;
  int height = getSize().height;

  int rowHt = height / (rows);
  int rowWid = width / (cols);

  for (int i = 0; i < rows ; i++) {
    for (int j = 0; i < rows ; j++) {
    double locationX = (i * rowHt);
    double locationY = (j * rowWid);


squares[i][j] = new Rectangle2D.Double(locationX,locationY, rows, cols);

1 个答案:

答案 0 :(得分:0)

我不知道您想将网格用作什么,但是我会使用JPanel绘制网格。这是一个工作示例。首先是JFrame:

package net.stackoverflow;

import javax.swing.JFrame;

public class MainFrame extends JFrame {

    static final long serialVersionUID = 19670916;

    protected GridPanel gridPanel = null;

    public MainFrame() {

        setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

        createGui();
        setVisible( true );
    }

    protected void createGui() {

        setSize( 600, 400 );
        setTitle( "Test Grid" );

        gridPanel = new GridPanel();

        add( gridPanel );
    }

    public static void main(String args[]) {

        MainFrame mf = new MainFrame();     
    }

}

现在是JPanel:

package net.stackoverflow;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.ArrayList;

import javax.swing.JPanel;

public class GridPanel extends JPanel {

    private static final long serialVersionUID = -5341480790176820445L;

    private final int NUM_SQUARES = 100;
    private final int RECT_SIZE = 10;
    private ArrayList<Rectangle> grid = null;

    public GridPanel() {

        setSize( 200, 200 );

        // Build the grid
        grid = new ArrayList<Rectangle>( NUM_SQUARES );
        for( int y=0; y < NUM_SQUARES / 10; ++y ) {
            for( int x=0; x < NUM_SQUARES / 10; ++x ) {
                Rectangle rect = new Rectangle( x * RECT_SIZE, y * RECT_SIZE, RECT_SIZE, RECT_SIZE );
                grid.add( rect );
            }
        }
    }

    @Override
    protected void paintComponent(Graphics g) {

        super.paintComponent( g );

        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 200, 200);

        // paint the grid
        for( Rectangle r : grid ) {

            g.setColor(Color.BLACK);
            g.drawRect( r.x, r.y, r.width, r.height );
        }
    }
}

paintComponent()中,您可以检查网格框是否还处于活动状态或其他状态,并根据需要绘制它。