java如何画方块


使用Java绘制方块的方法
在Java中,可以通过多种方式绘制方块,以下是几种常见的方法:
使用Swing和AWT绘制方块
import javax.swing.*;
import java.awt.*;
public class DrawSquare extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(50, 50, 100, 100); // x, y, width, height
}
public static void main(String[] args) {
JFrame frame = new JFrame("Draw Square");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawSquare());
frame.setSize(300, 300);
frame.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 DrawSquareFX extends Application {
@Override
public void start(Stage primaryStage) {
Rectangle square = new Rectangle(50, 50, 100, 100);
square.setFill(Color.BLUE);
Pane pane = new Pane();
pane.getChildren().add(square);
Scene scene = new Scene(pane, 300, 300);
primaryStage.setTitle("Draw Square");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
使用Graphics2D绘制带边框的方块
import javax.swing.*;
import java.awt.*;
public class DrawStyledSquare extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.GREEN);
g2d.fillRect(50, 50, 100, 100);
g2d.setStroke(new BasicStroke(3));
g2d.setColor(Color.BLACK);
g2d.drawRect(50, 50, 100, 100);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Styled Square");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawStyledSquare());
frame.setSize(300, 300);
frame.setVisible(true);
}
}
这些示例展示了在Java中绘制方块的不同方法,可以根据具体需求选择适合的方式。Swing和AWT适用于简单的图形绘制,而JavaFX提供了更现代的图形界面功能。Graphics2D则提供了更丰富的绘图选项。






