我试图在堆叠面板中绘制一些多边形。它们应该在我用鼠标点击的位置居中。它们是创建的,但它们始终位于边框面板的中间,而不是我单击的位置。有人能找到错误吗? (对不起,如果有一些意大利语单词,也很抱歉我的英语不好)。
public class Prova2 extends Application{
StackPane tavola = new StackPane();
@Override
public void start(Stage stage){
stage.setTitle("Peace!");
stage.setHeight(600);
stage.setWidth(600);
BorderPane layout = new BorderPane();
//LEFT
Label lb = new Label("DRAW");
VBox container = new VBox();
final ComboBox disegna = new ComboBox();
disegna.getItems().addAll(
"CIRCLE",
"TRIANGLE",
"SQUARE");
disegna.setValue("Choose");
final ColorPicker colorPicker = new ColorPicker(Color.BLACK);
TextField input = new TextField("");
container.getChildren().addAll(lb, disegna, colorPicker, input);
layout.setLeft(container);
BorderPane.setAlignment(container, Pos.CENTER);
//CENTER
tavola.setStyle("-fx-border-color: black;");
layout.setCenter(tavola);
//RIGHT
Button cancella = new Button("DELETE");
layout.setRight(cancella);
BorderPane.setAlignment(cancella, Pos.CENTER);
//AZIONI COMBOBOX
tavola.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent arg0) {
double x = arg0.getX();
double y = arg0.getY();
System.out.println("X:Y "+x+":"+y+"\n");
double m;
if(input.getText().isEmpty()){
m = 30;
}
else{
m=Double.parseDouble(input.getText());
}
if(disegna.getValue().equals("CIRCLE")){
Circle c = new Circle();
c.setCenterX(x);
c.setCenterY(y);
c.setRadius(m);
c.setOpacity(1);
c.setFill(colorPicker.getValue());
c.setStroke(Color.BLACK);
tavola.getChildren().add(c);
}
if(disegna.getValue().equals("TRIANGLE")){
Polygon t = new Polygon();
m=1.73*m;
t.setLayoutX(x);
t.setLayoutY(y);
t.getPoints().add(50.0);
t.getPoints().add(0.0);
t.getPoints().add(100.0);
t.getPoints().add(100.0);
t.getPoints().add(0.0);
t.getPoints().add(100.0);
t.setOpacity(1);
t.setFill(colorPicker.getValue());
t.setStroke(Color.BLACK);
tavola.getChildren().add(t);
}
if(disegna.getValue().equals("SQUARE")){
m=1.41*m;
Rectangle q = new Rectangle();
q.setX(x);
q.setY(y);
q.setHeight(m);
q.setWidth(m);
q.setOpacity(1);
q.setFill(colorPicker.getValue());
q.setStroke(Color.BLACK);
tavola.getChildren().add(q);
}
}
});
cancella.setOnMouseClicked(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent arg0) {
tavola.getChildren().removeAll(tavola.getChildren());
}
});
Scene scene = new Scene(layout);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
答案 0 :(得分:0)
原因是,您使用StackPane作为DrawPanel。默认情况下,StackPane将其添加的元素设置在窗格的中心,如果无法调整新子项的大小以填充它,如javadoc中所述:
stackpane将尝试调整每个子节点的大小以填充其内容 区域。如果孩子的大小不能填充堆叠窗格(或者 因为它不可调整大小或其最大大小阻止了它然后它 将使用alignment属性在区域内对齐 默认为Pos.CENTER。
出于绘图目的,我通常倾向于使用AnchorPane。除非您有使用StackPane的理由,否则您可能会尝试尝试。