确定javafx中的点击按钮

Determine clicked button in javafx

我有一段代码可以响应 desktop application 中的按钮点击。我有两个按钮做同样的事情:它们将左侧文本字段中的信息复制到剪贴板。我绑了一个method to each button。但它看起来很糟糕:

@FXML
public void copyToClipboardRaw() {
    if(code == null || code.isEmpty()) {
        nothingToCopyAlert();
    } else {
        Clipboard clipboard = Clipboard.getSystemClipboard();
        ClipboardContent content = new ClipboardContent();
        content.putString(rawCode.getText());
        clipboard.setContent(content);
    }
}

@FXML
public void copyToClipboardHTML() {
    if(code == null || code.isEmpty()) {
        nothingToCopyAlert();
    } else {
        Clipboard clipboard = Clipboard.getSystemClipboard();
        ClipboardContent content = new ClipboardContent();
        content.putString(codeForHTML.getText());
        clipboard.setContent(content);
    }
}

如何将一种方法绑定到所有按钮,并在该方法中确定单击了哪个按钮?

您可以使用按钮的文本 属性,或者也可以使用 userData 属性。例如:

<Button text="Copy as raw" userData="raw" onAction="#copyToClipboard" />
<Button text="Copy as HTML" userData="html" onAction="#copyToClipboard" />

并在控制器中 class

@FXML
private void copyToClipboard( ActionEvent event )
{
    Button button = (Button) event.getSource();
    String type = button.getUserData();
    if ("html".equals(type)) {
        // copy as html
    } else if ("raw".equals(type)) {
        // copy as raw
    }
}

为什么不把通用代码分解成一个方法:

@FXML
public void copyToClipboardRaw() {
    copyToClipboard(rawCode);
}

@FXML
public void copyToClipboardHTML() {
    copyToClipboard(codeForHTML);
}

private void copyToClipboard(TextField source) {
    if(code == null || code.isEmpty()) {
        nothingToCopyAlert();
    } else {
        Clipboard clipboard = Clipboard.getSystemClipboard();
        ClipboardContent content = new ClipboardContent();
        content.putString(source.getText());
        clipboard.setContent(content);
    }
}