java如何画方格
使用 Java 绘制方格的方法
使用 Graphics 绘制方格
在 Java 中,可以通过 Graphics 或 Graphics2D 类绘制方格。以下是一个简单的示例代码,使用 JFrame 和 JPanel 绘制方格:
import javax.swing.*;
import java.awt.*;
public class DrawGrid extends JPanel {
private int rows;
private int cols;
private int cellSize;
public DrawGrid(int rows, int cols, int cellSize) {
this.rows = rows;
this.cols = cols;
this.cellSize = cellSize;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
g.drawRect(j * cellSize, i * cellSize, cellSize, cellSize);
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Grid Drawing");
DrawGrid grid = new DrawGrid(5, 5, 50);
frame.add(grid);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
使用 BufferedImage 绘制方格
如果需要将方格保存为图像文件,可以使用 BufferedImage 和 Graphics2D:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class SaveGridToImage {
public static void main(String[] args) throws Exception {
int rows = 5;
int cols = 5;
int cellSize = 50;
int width = cols * cellSize;
int height = rows * cellSize;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, width, height);
g2d.setColor(Color.BLACK);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
g2d.drawRect(j * cellSize, i * cellSize, cellSize, cellSize);
}
}
ImageIO.write(image, "png", new File("grid.png"));
g2d.dispose();
}
}
使用 JavaFX 绘制方格
如果使用 JavaFX,可以通过 Canvas 和 GraphicsContext 绘制方格:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class JavaFXGrid extends Application {
@Override
public void start(Stage stage) {
int rows = 5;
int cols = 5;
int cellSize = 50;
int width = cols * cellSize;
int height = rows * cellSize;
Canvas canvas = new Canvas(width, height);
GraphicsContext gc = canvas.getGraphicsContext2D();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
gc.strokeRect(j * cellSize, i * cellSize, cellSize, cellSize);
}
}
StackPane root = new StackPane(canvas);
stage.setScene(new Scene(root));
stage.setTitle("JavaFX Grid");
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
自定义方格样式
可以通过调整颜色、线条粗细和填充效果来自定义方格样式。例如,在 Graphics2D 中设置线条粗细:

g2d.setStroke(new BasicStroke(2)); // 设置线条宽度为 2 像素
g2d.setColor(Color.RED); // 设置线条颜色为红色
总结
以上方法分别适用于 Swing、JavaFX 和图像生成场景,可以根据具体需求选择合适的实现方式。






