题目:*18.19 (思瑞平斯基三角形)
修改程序清单18-9, 开发一个程序让用户使用 “+” 和 "-” 按钮将当前阶数增1或减1,如图 18 -12a 所示。初始阶数为0。如果当前阶数为0,就忽略按钮。
-
代码示例
编程练习题18_19SierpinskiTriangle.java
package chapter_18;
import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class 编程练习题18_19SierpinskiTriangle extends Application{
private static int order = 0;
@Override
public void start(Stage primaryStage) throws Exception {
SierpinskiTrianglePane trianglePane = new SierpinskiTrianglePane();
Button btAdd = new Button("+");
btAdd.setOnMouseClicked(e ->{
trianglePane.increaseByOne();
});
Button btSubtract = new Button("-");
btSubtract.setOnMouseClicked(e ->{
trianglePane.decreaseByOne();
});
HBox hBox = new HBox(10);
hBox.getChildren().addAll(btAdd,btSubtract);
hBox.setAlignment(Pos.CENTER);
BorderPane borderPane = new BorderPane();
borderPane.setCenter(trianglePane);
borderPane.setBottom(hBox);
Scene scene = new Scene(borderPane, 200, 210);
primaryStage.setTitle("编程练习题18_19SierpinskiTriangle");
primaryStage.setScene(scene);
primaryStage.show();
}
static class SierpinskiTrianglePane extends Pane{
private int order = 0;
public void setOrder(int order) {
this.order = order;
paint();
}
SierpinskiTrianglePane(){
}
protected void paint() {
Point2D p1 = new Point2D(getWidth()/2, 10);
Point2D p2 = new Point2D(10, getHeight() - 10);
Point2D p3 = new Point2D(getWidth()-10, getHeight() -10);
this.getChildren().clear();
displayTriangles(order,p1,p2,p3);
}
private void displayTriangles(int order,Point2D p1,
Point2D p2,Point2D p3) {
if(order < 0) {
System.out.println("Order must be non-negative");
return;
}
if(order == 0){
/*Polygon triangle = new Polygon();
triangle.getPoints().addAll(p1.getX(),p1.getY()
,p2.getX(),p2.getY(),p3.getX(),p3.getY());
triangle.setStroke(Color.BLACK);
triangle.setFill(Color.WHITE);
this.getChildren().add(triangle);*/
Line l1 = new Line(p1.getX(), p1.getY(), p2.getX(), p2.getY());
Line l2 = new Line(p2.getX(), p2.getY(), p3.getX(), p3.getY());
Line l3 = new Line(p3.getX(), p3.getY(), p1.getX(), p1.getY());
this.getChildren().addAll(l1,l2,l3);
}else {
Point2D p12 = p1.midpoint(p2);
Point2D p23 = p2.midpoint(p3);
Point2D p31 = p3.midpoint(p1);
displayTriangles(order-1, p1, p12, p31);
displayTriangles(order-1, p12, p2, p23);
displayTriangles(order-1, p31, p23, p3);
}
}
public void decreaseByOne() {
if (order > 0) {
setOrder(order - 1);
}
}
public void increaseByOne() {
setOrder(order + 1);
}
}
public static void main(String[] args) {
Application.launch(args);
}
}
-
结果展示