JavaFX 矩形椭圆

JavaFX教程 – JavaFX矩形椭圆

avaFX Shape类定义了常见的形状,如线,矩形,圆,Arc,CubicCurve,Ellipse和QuadCurve。

在场景图上绘制矩形需要宽度,高度和左上角的(x,y)位置。

要在JavaFX中绘制一个矩形,我们可以使用 javafx.scene.shape.Rectangle 类。

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class Main extends Application {
    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("");
        Group root = new Group();
        Scene scene = new Scene(root, 300, 250, Color.WHITE);

        Rectangle r = new Rectangle();
        r.setX(50);
        r.setY(50);
        r.setWidth(200);
        r.setHeight(100);

        root.getChildren().add(r); 
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

上面的代码生成以下结果。


圆角矩形

Rectangle 类实现圆弧宽度和圆弧高度。我们可以使用这些功能来绘制圆角矩形。

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class Main extends Application {

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

  @Override
  public void start(Stage primaryStage) {
    Group group = new Group();

    Rectangle rect = new Rectangle(20,20,200,200);

    rect.setArcHeight(15);
    rect.setArcWidth(15);

    rect.setStroke(Color.BLACK);
    group.getChildren().add(rect);

    Scene scene = new Scene(group, 300, 200);
    primaryStage.setScene(scene);
    primaryStage.show();
  }
}

上面的代码生成以下结果。


椭圆

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.effect.DropShadow;
import javafx.scene.paint.Color;
import javafx.scene.shape.Ellipse;
import javafx.stage.Stage;

public class Main extends Application {
  public static void main(String[] args) {
    Application.launch(args);
  }

  @Override
  public void start(Stage primaryStage) {
    primaryStage.setTitle("");
    Group root = new Group();
    Scene scene = new Scene(root, 300, 250, Color.WHITE);

    Group g = new Group();

    DropShadow ds = new DropShadow();
    ds.setOffsetY(3.0);
    ds.setColor(Color.color(0.4, 0.4, 0.4));

    Ellipse ellipse = new Ellipse();
    ellipse.setCenterX(50.0f);
    ellipse.setCenterY(50.0f);
    ellipse.setRadiusX(50.0f);
    ellipse.setRadiusY(25.0f);
    ellipse.setEffect(ds);

    g.getChildren().add(ellipse);

    root.getChildren().add(g);
    primaryStage.setScene(scene);
    primaryStage.show();
  }
}

上面的代码生成以下结果。


版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《JavaFX 矩形椭圆》
文章链接:https://zhuji.vsping.com/293809.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。