简体   繁体   English

确定javafx中的单击按钮

[英]Determine clicked button in javafx

I have a piece of code that response to click on buttons in desktop application . 我有一段代码可以响应单击desktop application按钮。 I have two buttons that do the same thing: they copy to clipboard information from the text field to the left. 我有两个功能相同的按钮:它们将文本字段左侧的内容复制到剪贴板中。 I have tied a method to each button . 我已经method to each button绑定了一种method to each button But it looks like shit: 但是看起来很烂:

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

How can I bind one method to all buttons and determine in this method which button was clicked? 如何将一个方法绑定到所有按钮,并确定在该方法中单击了哪个按钮?

You may use the text property of the buttons, or use userData property as well. 您可以使用按钮的text属性,也可以使用userData属性。 For example: 例如:

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

and in controller 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
    }
}

Why not factor out the common code into a single method: 为什么不将通用代码分解为一个方法:

@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