【问题标题】:Creating a Grid with rectangles使用矩形创建网格
【发布时间】:2018-12-10 20:09:22
【问题描述】:

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

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);

【问题讨论】:

  • 您显示的代码非常不完整。有对getSize() 等不可见部分的引用,还有不完整的块。此外,根本没有使用函数参数,它们的预期功能也不清楚。最后但并非最不重要的一点是,它包含诸如 100 之类的“幻数”,这些未在要求中解释。您应该澄清您的问题并指出预期的行为。什么是输入?预期的输出是什么?

标签: java graphics grid rectangles


【解决方案1】:

我不知道你想用网格做什么,但我会使用 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() 中,您可以检查网格框是否处于活动状态或其他任何内容,然后随意绘制。

【讨论】:

    猜你喜欢
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多