简体   繁体   中英

Determine clicked button in javafx

I have a piece of code that response to click on buttons in 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 . 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. 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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