在Java中,可以使用不同的庫和框架來繪制正方形。以下是一些常見的方法:
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);
}
}
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);
}
}
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庫和框架繪制正方形。你可以根據項目需求和個人喜好選擇合適的方法。