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

   2024-09-30 2210
核心提示:在Java中,可以使用不同的库和框架来绘制正方形。以下是一些常见的方法:使用Java AWT(Abstract Window Toolkit)库:import ja

在Java中,可以使用不同的库和框架来绘制正方形。以下是一些常见的方法:

使用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);    }}
使用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);    }}
使用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库和框架绘制正方形。你可以根据项目需求和个人喜好选择合适的方法。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号