本文介绍了JavaFX中按钮的自定义碰撞形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建自定义按钮形状很容易,但是如何确保新形状也是按钮本身的碰撞盒"呢?

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?

完整的示例:

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;
    }
}

推荐答案

致电

aButton.setPickOnBounds(false);

这指示JavaFX仅在鼠标位于非透明像素上方时才将鼠标视为位于按钮上方,而不是默认值(即鼠标坐标与按钮的矩形边界相交).

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).

这篇关于JavaFX中按钮的自定义碰撞形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 10:36