Issue
I'm a beginner java programmer and I'm making a small app where I can enter my school marks and see my total score. I have 2 classes in total (1 for javafx layout and 1 for my Methods), and I'm trying to change the color of a label (.setTextFill) which is in the main class with a method in the methods class.
I have tried making an object of the main class but this gives an error: java.lang.reflect.InvocationTargetException.
public void start(Stage primaryStage)throws Exception{
totalPercent = new Label(Methods.getTotalPercent());
totalPercent.setTextFill(Color.web("#4ecf17"));
}
//next code is in a different class
public void setPercentColor(){
if(percent < 50){
totalPercent.setTextFill(Color.web("#ff0000"));
}else if(percent >= 50 && percent < 60){
totalPercent.setTextFill(Color.web("#ff7700"));
}else if (percent >= 60 && percent < 100){
totalPercent.setTextFill(Color.web("#59ff00"));
}else{
totalPercent.setTextFill(Color.web("#000000"));
}
}
So basically I don't know how to change the color from the label 'totalPercent' with a method that's located in a different class.
Solution
The design of your classes is not done well considering the setPercentColor
method: It controls the details of the representation of some view managed by another class.
I recommend redesigning Methods
to provide a property and letting the other class decide on what to do with this value.
In this case you could add a ReadOnlyIntegerProperty percent
instead of using a field. This way the other class can use bindings/listeners to update the view and the only thing Methods
needs to worry about is updating the property.
In Methods
// private int percent;
private final ReadOnlyIntegerWrapper percent = new ReadOnlyIntegerWrapper();
public ReadOnlyIntegerProperty percentProperty() {
return percent.getReadOnlyProperty();
}
public int getPercent() {
return percent.get();
}
...
// percent = i
percent.set(i); // replace assinment to int field with setting the property
Other class
public void start(Stage primaryStage)throws Exception{
totalPercent = new Label();
totalPercent.textProperty().bind(Methods.percentProperty().asString());
final Color color560 = Color.web("#ff7700");
final Color color100 = Color.web("#59ff00");
totalPercent.textFillProperty().bind(Bindings.createObjectBinding(() -> {
int percent = Methods.getPercent();
if(percent < 50) {
return Color.RED;
} else if(percent < 60) {
return color60;
}else if (percent < 100){
return color100;
} else {
return Color.BLACK;
}
}, Methods.percentProperty()));
}
BTW: I recommend choosing a more meaningful name for the Methods
class: Most classes contain method implementations, so the name contains basically no valuable info to someone reading the code.
Answered By - fabian
Answer Checked By - Mary Flores (JavaFixing Volunteer)