确定javafx中的单击按钮

时间:2016-01-18 11:15:48

标签: java button javafx refactoring fxml

我有一段代码响应点击desktop application中的按钮。我有两个按钮执行相同的操作:它们从文本字段向左复制到剪贴板信息。我绑了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);
    }
}

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

2 个答案:

答案 0 :(得分:4)

您可以使用按钮的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
    }
}

答案 1 :(得分:2)

为什么不将公共代码分解为单个方法:

mode= loop1 or loop2
command1="screen -dm -S name feh *.jpg"

if [ "$(screen -S loop1 -X select . ; echo $?)" != 0 ] && [[ $mode !=     "loop1" ]];then 
eval "${command1/name/loop1}"
elif [ "$(screen -S loop2 -X select . ; echo $?)" != 0 ] && [[ $mode !=     "loop2" ]] ;then
eval "${command1/name/loop2}"
else 
echo "error"
fi