繁体   English   中英

确定javafx中的单击按钮

[英]Determine clicked button in javafx

我有一段代码可以响应单击desktop application按钮。 我有两个功能相同的按钮:它们将文本字段左侧的内容复制到剪贴板中。 我已经method to each button绑定了一种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);
    }
}

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

您可以使用按钮的text属性,也可以使用userData属性。 例如:

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

并在控制器类中

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM