如何用java画矩形


使用Java绘制矩形的方法
在Java中,可以通过多种方式绘制矩形,以下是几种常见的方法:
使用Swing的Graphics类
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, 100); // 绘制空心矩形
g.fillRect(200, 50, 100, 100); // 绘制实心矩形
}
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);
}
}
使用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) {
Rectangle rect1 = new Rectangle(50, 50, 100, 100);
rect1.setFill(Color.TRANSPARENT);
rect1.setStroke(Color.BLACK);
Rectangle rect2 = new Rectangle(200, 50, 100, 100);
rect2.setFill(Color.BLUE);
Pane root = new Pane();
root.getChildren().addAll(rect1, rect2);
Scene scene = new Scene(root, 400, 200);
primaryStage.setTitle("绘制矩形");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
使用AWT的Graphics2D类
import java.awt.*;
import java.awt.geom.Rectangle2D;
public class DrawRectangleAWT extends Frame {
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.draw(new Rectangle2D.Double(50, 50, 100, 100)); // 空心矩形
g2d.fill(new Rectangle2D.Double(200, 50, 100, 100)); // 实心矩形
}
public static void main(String[] args) {
DrawRectangleAWT frame = new DrawRectangleAWT();
frame.setSize(400, 200);
frame.setVisible(true);
}
}
参数说明
drawRect(x, y, width, height)或fillRect(x, y, width, height)方法中:x和y表示矩形左上角的坐标width和height表示矩形的宽度和高度
- 可以通过
setColor()方法设置绘制颜色 - 在 JavaFX 中,可以通过
setStroke()和setFill()分别设置边框和填充颜色
以上方法可以根据具体需求选择适合的图形库来实现矩形绘制。






