setOnAction restrictions and datepicker class

Multi tool use


setOnAction restrictions and datepicker class
I'm writing an application involved in time difference, there is something I don't get it,
final DatePicker datePick=new DatePicker();
LocalDate time;
Label label=new Label();
datePick.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent e){
time=datePick.getValue();//doesn't work, must 'LocalDate time=datePick.getValue();
label.setText(time);//doesn't work must label.setText("Time now:"+time)
}
});
It gives an error saying "Local variables referenced from an inner class must be final or effectively fine", anyway, all I did, declare 'time' variable inside setOnAction() and it worked, so what was wrong? and 'label.setText(time);' if I don't write some text inside, like 'label.setText("Time now: "+ time);' ,won't work too, that's weird, yet why?
label.setText(datePicekr.getValue());
please read docs.oracle.com/javase/tutorial/java/javaOO/index.html and other chapters on language basics @Sedrick think again <g> I know that you know the return type of picker.getValue :)
– kleopatra
11 mins ago
1 Answer
1
Java restricts local variables you access from a anonymus class/lambda expression to those that never change their values after assignment (i.e. thoser the compiler wouldn't complain about, if you declared them as final
). If you could write to the local variable from a anonymus class this would violate this condition. It's not possible to write to local variables of the containing method from anonymus classes for this reason.
final
You should declare variables in the scope where they are needed anyways.
As for label.setText(time);
:
label.setText(time);
Label.setText
is a method with a String
parameter. Since String
is not a supertype of LocalDate
, a simple assignment won't work. You need to convert the date to a String
. String concatenation does this automatically, i.e. the +
operator receiving a String s
as first operand and a Object o
as second operand outputs the concatenation of s
and Objects.toString(o)
.
Label.setText
String
String
LocalDate
String
+
String s
Object o
s
Objects.toString(o)
You could simply invoke toString
yourself:
toString
label.setText(time.toString());
Or use a more sophisticated method for convertion to string.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Why not just do
label.setText(datePicekr.getValue());
?– Sedrick
3 hours ago