netbeans 是否可以创建“集中式”MouseEvent?

js81xvg6  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(198)

我有这两个MouseEvent,我希望它们“集中化”,因为我有其他节点也会做同样的事情。我知道如果创建多个MouseEvent,就可以做到这一点,但我认为一定有一个更短的方法。

public class scMain implements Initializable {

@FXML
private Button btnView, btnView2;
@FXML
private HBox hboxView, hboxView2;

public void translateTransition(Node node) {
    TranslateTransition translate = new TranslateTransition();
    translate.setNode(node);
    // ...animation stuff   
    translate.play();
}

public void fadeOffTransition(Node node) {
    FadeTransition fade = new FadeTransition();
    fade.setNode(node);
    // ...animation stuff  
    fade.play();
}

public void fadeInTransition(Node node) {
    FadeTransition fade = new FadeTransition();
    fade.setNode(node);
    // ...animation stuff  
    fade.play();
}

@FXML
void btnMouseEnter(MouseEvent event) {
    fadeOffTransition(btnView);
    hboxView.setVisible(true);
    translateTransition(hboxView);
}

@FXML
void btnMouseExit(MouseEvent event) {
    fadeInTransition(btnView);
    hboxView.setVisible(false);
}}

我试过但显然不起作用的是:

@FXML
void btnMouseEnter(MouseEvent event, Node first, Node second) {
    fadeOffTransition(first);
    second.setVisible(true);
    translateTransition(second);
}

@FXML
void btnMouseExit(MouseEvent event, Node first, Node second) {
    fadeInTransition(first);
    second.setVisible(false);
}

@Override
public void initialize(URL url, ResourceBundle rb) {
   btnMouseEnter(event, btnView2, hboxView2); //error cannot find symbol
   btnMouseExit(event, btnView2, hboxView2); //error cannot find symbol
}

如有任何建议,我们将不胜感激。

4bbkushb

4bbkushb1#

intialize()方法中注册事件处理程序,而不是在FXML中注册。从FXML文件中删除onMouseEnteronMouseExit属性,并修改控制器,如下所示:

void btnMouseEnter(Node first, Node second) {
    fadeOffTransition(first);
    second.setVisible(true);
    translateTransition(second);
}

void btnMouseExit(Node first, Node second) {
    fadeInTransition(first);
    second.setVisible(false);
}

@Override
public void initialize(URL url, ResourceBundle rb) {
   btnView2.setOnMouseEnter(e -> btnMouseEnter(btnView2, hboxView2));
   btnView2.setOnMouseExit(e -> btnMouseExit(btnView2, hboxView2));
}

您还可以明显减少代码,例如:

private void registerMouseHandlers(Button button, Node target) {
    button.setOnMouseEnter(e -> btnMouseEnter(button, target));
    button.setOnMouseExit(e -> btnMouseExit(button, target));
}

@Override
public void initialize(URL location, ResourceBundle resources) {
    registerMouseHandlers(btnView, hboxView);
    registerMouseHandlers(btnView2, hboxView2);
}

如果您有相当多的这样的代码,那么这样做也可能更有效(就代码行而言)

@Override
public void initialize(URL location, ResourceBundle resources) {
    List<Button> buttons = List.of(btnView, btnView2);
    List<Node> targets = List.of(hboxView, hboxView2);
    for (int i = 0 ; i < buttons.size() ; i++) {
        registerMouseHandlers(buttons.get(i), targets.get(i));
    }
}

您还可以考虑创建一个封装button和hbox的自定义组件,该组件只实现单个button-hbox对的事件处理程序,然后使用fx:include将它们包含在FXML中。

相关问题