在我的程序中,我必须通过单击单选按钮来更改示例字符串的颜色。但是,每次点击它们时,我都会不断收到错误消息。我不断收到此错误。我也在使用e(fx)clipse对此进行编码。
产生于:java.lang.ClassCastException: 无法将javafx.graphics@10.0.2/javafx.scene.paint.Color强制转换为 javafx.graphics@10.0.2/javafx.scene.text.Text位于 employee.view.MainController.colorRadioButtonSelected(MainController.java:83) 打包employee.view;
import javafx.beans.value.ChangeListener;
import javafx.scene.paint.Paint;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ListView;
public class MainController {
@FXML
private BorderPane myPane;
@FXML
private RadioButton blackRadioButton;
@FXML
private ToggleGroup colorToggleGroup;
@FXML
private RadioButton redRadioButton;
@FXML
private RadioButton blueRadioButton;
@FXML
private RadioButton greenRadioButton;
@FXML
private ListView<String> mylistView;
@FXML
private CheckBox boldCheckBox;
@FXML
private CheckBox italicCheckBox;
String Text;
Text sample=new Text(50,300,"SAMPLE");
FontWeight weight = FontWeight.NORMAL; // FontWeight.BOLD is boldface
FontPosture posture = FontPosture.REGULAR; // FontPosture.ITALIC is italic
int size=18;
boolean fontBold = false;
boolean fontItalic = false;
public void initialize() {
blackRadioButton.setUserData(Color.BLACK);
redRadioButton.setUserData(Color.RED);
greenRadioButton.setUserData(Color.GREEN);
blueRadioButton.setUserData(Color.BLUE);
myPane.getChildren( ).add( sample );
sample.setFont(Font.font("Verdana", weight, posture, size));
}
@FXML
void boldCheckBoxSelected(ActionEvent event) {
}
@FXML
void colorRadioButtonSelected(ActionEvent event) {
sample= (javafx.scene.text.Text) colorToggleGroup.getSelectedToggle().getUserData();
}
@FXML
void italicCheckBoxSelected(ActionEvent event) {
}
}
答案 0 :(得分:1)
您将数据设置为Color
blackRadioButton.setUserData(Color.BLACK);
redRadioButton.setUserData(Color.RED);
greenRadioButton.setUserData(Color.GREEN);
blueRadioButton.setUserData(Color.BLUE);
但是您尝试将其转换为Text
(javafx.scene.text.Text) colorToggleGroup.getSelectedToggle().getUserData();
要解决此问题,您可以使用switch语句或多个if语句根据选择的颜色来设置sample
对象。示例if语句:
if ((Color) colorToggleGroup.getSelectedToggle().getUserData() == Color.BLUE) {
sample = new Text(50, 300, "Something");
}
或者,您可以将单选按钮的数据设置为Text
,例如:
blueRadioButton.setUserData(new Text(50, 300, "Something"));