java如何画一个矩形
使用Graphics类绘制矩形
在Java中,可以通过java.awt.Graphics类提供的drawRect和fillRect方法绘制矩形。这两个方法分别用于绘制空心矩形和填充矩形。

import javax.swing.*;
import java.awt.*;
public class DrawRectangle extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 绘制空心矩形
g.drawRect(50, 50, 100, 80);
// 绘制填充矩形
g.fillRect(200, 50, 100, 80);
}
public static void main(String[] args) {
JFrame frame = new JFrame("绘制矩形");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawRectangle());
frame.setSize(400, 200);
frame.setVisible(true);
}
}
使用Graphics2D类绘制矩形
Graphics2D是Graphics的子类,提供了更丰富的绘图功能。可以通过setStroke方法设置线条样式,例如线条宽度。

import javax.swing.*;
import java.awt.*;
public class DrawRectangle2D extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// 设置线条宽度为3像素
g2d.setStroke(new BasicStroke(3));
// 绘制空心矩形
g2d.drawRect(50, 50, 100, 80);
// 绘制填充矩形
g2d.setColor(Color.BLUE);
g2d.fillRect(200, 50, 100, 80);
}
public static void main(String[] args) {
JFrame frame = new JFrame("绘制矩形");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawRectangle2D());
frame.setSize(400, 200);
frame.setVisible(true);
}
}
使用JavaFX绘制矩形
在JavaFX中,可以通过Rectangle类创建矩形,并设置填充颜色、边框颜色等属性。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class DrawRectangleFX extends Application {
@Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
// 创建空心矩形
Rectangle rect1 = new Rectangle(50, 50, 100, 80);
rect1.setFill(Color.TRANSPARENT);
rect1.setStroke(Color.BLACK);
// 创建填充矩形
Rectangle rect2 = new Rectangle(200, 50, 100, 80);
rect2.setFill(Color.BLUE);
pane.getChildren().addAll(rect1, rect2);
Scene scene = new Scene(pane, 400, 200);
primaryStage.setTitle("绘制矩形");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
使用BufferedImage绘制矩形
在非GUI环境下,可以通过BufferedImage和Graphics2D绘制矩形并保存为图片文件。
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class DrawRectangleToImage {
public static void main(String[] args) throws Exception {
BufferedImage image = new BufferedImage(400, 200, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
// 设置背景色为白色
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, 400, 200);
// 绘制空心矩形
g2d.setColor(Color.BLACK);
g2d.drawRect(50, 50, 100, 80);
// 绘制填充矩形
g2d.setColor(Color.BLUE);
g2d.fillRect(200, 50, 100, 80);
g2d.dispose();
// 保存为PNG文件
ImageIO.write(image, "png", new File("rectangle.png"));
}
}


