Reputation: 689
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 amethod 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?
Upvotes: 1
Views: 2508
Reputation: 209684
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);
}
}
Upvotes: 2
Reputation: 49215
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
}
}
Upvotes: 4