溫馨提示×

Java繪制正方形的方法有哪些

小樊
83
2024-08-30 07:22:53
欄目: 編程語言

在Java中,可以使用不同的庫和框架來繪制正方形。以下是一些常見的方法:

  1. 使用Java AWT(Abstract Window Toolkit)庫:
import java.awt.*;
import javax.swing.*;

public class DrawSquare extends JFrame {
    public DrawSquare() {
        setSize(400, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.setColor(Color.BLUE);
        g.fillRect(50, 50, 200, 200); // x, y, width, height
    }

    public static void main(String[] args) {
        DrawSquare ds = new DrawSquare();
        ds.setVisible(true);
    }
}
  1. 使用Java2D API:
import java.awt.*;
import javax.swing.*;

public class DrawSquare extends JFrame {
    public DrawSquare() {
        setSize(400, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.BLUE);
        g2d.fillRect(50, 50, 200, 200); // x, y, width, height
    }

    public static void main(String[] args) {
        DrawSquare ds = new DrawSquare();
        ds.setVisible(true);
    }
}
  1. 使用JavaFX:
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 DrawSquare extends Application {
    @Override
    public void start(Stage primaryStage) {
        Pane root = new Pane();
        Rectangle square = new Rectangle(50, 50, 200, 200);
        square.setFill(Color.BLUE);
        root.getChildren().add(square);
        Scene scene = new Scene(root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

這些示例展示了如何使用不同的Java庫和框架繪制正方形。你可以根據(jù)項目需求和個人喜好選擇合適的方法。

0