[英]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.