本题的难点主要有两个:
第一:如何实现一个六边形(可以记住这个方法)主要是通过公式来获得各个顶点
第二:如何通过按钮变换多边形的边数。首先点击按钮时要将原多边形清除,我刚开始想到的是利用面板的clear来清除,后来发现行不通。于是想到为什么不直接清除多边形的各个顶点,可以直接利用list.clear()重新加顶点进去。详细代码如下:
import javafx.application.Application;
import javafx.collections.ObservableList;
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.paint.Color;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;
public class PolygonChange extends Application{
static int start=6;//边数
static int add=1;//增加减少1条边
public static void main(String[] args) {
// TODO Auto-generated method stub
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
// TODO Auto-generated method stub
double paneWidth=200;
double paneHeight=200;
double radius=80;//设置初始六边形的边长
BorderPane pane=new BorderPane();
Polygon p=new Polygon();
p.setFill(Color.WHITE);
p.setStroke(Color.BLACK);
ObservableList<Double> list=p.getPoints();
for(int i=0;i<start;i++) {
list.add(paneWidth/2+radius*Math.cos(i*2*Math.PI/start));//获得多边形各点的X坐标
list.add(paneHeight/2+radius*Math.sin(i*2*Math.PI/start));//获得多边形各点的Y坐标
}
pane.setCenter(p);
HBox hBox=new HBox(5);
Button bt1=new Button("+");
Button bt2=new Button("-");
hBox.getChildren().addAll(bt1,bt2);
hBox.setAlignment(Pos.CENTER);
pane.setBottom(hBox);
bt1.setOnAction(e ->{
list.clear();//改变多边形边数的关键,清除原始多边形的各个顶点
start+=add;//边数加1
for(int i=0;i<start;i++) {
list.add(paneWidth/2+radius*Math.cos(i*2*Math.PI/start));
list.add(paneHeight/2+radius*Math.sin(i*2*Math.PI/start));
}
});
bt2.setOnAction(e ->{
list.clear();
start-=add;
for(int i=0;i<start;i++) {
list.add(paneWidth/2+radius*Math.cos(i*2*Math.PI/start));
list.add(paneHeight/2+radius*Math.sin(i*2*Math.PI/start));
}
});
Scene scene=new Scene(pane,paneWidth,paneHeight);
stage.setTitle("JavaFx");
stage.setScene(scene);
stage.show();
}
}