我如何 return 在代码中使用 javafx 中的颜色文本?

how can I return text in code with color in javafx?

有我的代码:

public String changePassword(String _login, String _pass1, String _pass2) {
 if (_pass2 != _pass1) {
  return "Passwords not match!"; //Want to be red color
 } else {
  executeQuery("UPDATE persons SET username = username, password = password WHERE username = '" + _login + "' AND password = '" + _pass2 + "'");
  return "Well done!"; // Want to be green color
 }
}

在我的 fxml 文件中,此文本将显示在标签中。

您可以 return 布尔值而不是 return 字符串。

public boolean changePassword(...) {
    if(not correct) {
        return false;
    }
    return true;
}

然后你调用这个方法的地方你可以检查这个方法的结果是什么并采取相应的行动:

if(changePassword(...)) {
    //set label color to green and set text to well done
} else {
    //set label color to red...
}

此外,如果您不知道,可以通过控制器或根结构访问 FXML 节点。我更喜欢根结构。您可以执行 @FXML private Label idOfLabelInFxml; 然后通过那里访问它。可以在此处找到更多信息:get FXML file nodes using java code