Reputation: 13
Creating a custom button shape is easily done, but how is it possible to make sure that the new shape is also the "collision box" of the button itself?
In this case I created two hexagnol shaped buttons and aligned them properly. The problem is that the collision box of the buttons is still rectangular and when you move the mouse from the upper button to the lower one you will notice that the collision box is strictly rectangular and makes the custom shapes kind of useless.
Any way to create custom collision shapes or collision checks?
Full working example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;
public class Test extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Pane aPane = new Pane();
aPane.setPrefWidth(100);
aPane.setPrefHeight(100);
aPane.getChildren().add(createHexAt(10, 10));
aPane.getChildren().add(createHexAt(35, 45));
Scene aScene = new Scene(aPane);
primaryStage.setScene(aScene);
primaryStage.show();
}
private Button createHexAt(double xPos, double yPos) {
Button aButton = new Button();
aButton.setLayoutX(xPos);
aButton.setLayoutY(yPos);
aButton.setPrefWidth(50);
aButton.setPrefHeight(50);
double[] path = new double[12];
for (int q = 0; q < 6; q++) {
double x = Math.cos(Math.PI / 3.0 * q + Math.PI / 2.0);
double y = Math.sin(Math.PI / 3.0 * q + Math.PI / 2.0);
path[q * 2] = x;
path[q * 2 + 1] = y;
}
Polygon aPoly = new Polygon(path);
aButton.setShape(aPoly);
return aButton;
}
}
Upvotes: 1
Views: 1284
Reputation: 209225
Call
aButton.setPickOnBounds(false);
This instructs JavaFX to only consider the mouse as being over the button if it is over a non-transparent pixel, instead of the default (which is that the mouse coordinates intersect the rectangular bounds of the button).
Upvotes: 3