我有一个带有默认形状的HBox和两个按钮。每个对象都可以生成一个三角形并将其放置在SHAPE ObjectProperty中。我的问题是我没有办法将HBox内容绑定到ObjectProperty。请问有人对如何实现这一目标有想法吗?
package stackOverflow;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;
public class BoxContent extends Application
{
// property accessible to buttons
ObjectProperty SHAPE = new SimpleObjectProperty();
// shape method
Polygon getDownGreenTriangle() {
Polygon polygon = new Polygon(0.0, 0.0, 15.0, 0.0, 7.5, 15.0);
polygon.setFill(Color.LIGHTGREEN);
return polygon; }
// shape method
Polygon getUpRedTriangle() {
Polygon polygon = new Polygon(0.0, 0.0, 15.0, 0.0, 7.5, 15.0);
polygon.setFill(Color.RED);
SHAPE.set(polygon);
return polygon; }
// default circle
Circle circle = new Circle(10, Color.GREY);
@Override
public void start(Stage stage) throws Exception {
// box not available to buttons (how to bind content?)
HBox hbox = new HBox();
hbox.getChildren().add(circle);
// buttons
Button GREEN = new Button("Green");
Button RED = new Button("Red");
// actions
GREEN.setOnAction(e -> {
Platform.runLater(() -> {
SHAPE.set(getDownGreenTriangle());
}); });
RED.setOnAction(e -> {
Platform.runLater(() -> {
SHAPE.set(getDownGreenTriangle());
}); });
// pane
GridPane root = new GridPane();
root.setHgap(10);
root.setVgap(10);
root.add(hbox, 1, 1);
root.add(RED, 2, 1);
root.add(GREEN, 3, 1);
Scene scene = new Scene(root, 160, 45);
stage.setScene(scene);
stage.show();
} // end start
public static void main(String[] args)
{
launch(args);
}
}