gpt4 book ai didi

java - 如何修改调用更改监听器的 javafx 对象属性的对象?

转载 作者:行者123 更新时间:2023-12-04 20:44:03 25 4
gpt4 key购买 nike

我有一个 javafx.beans.property.ObjectProperty<Calendar> .我如何修改日历,以便 javafx 注册它并调用更改监听器?

所以,当我尝试设置日历字段时 Calendar.YEAR有没有比

更好的解决方案
Calendar c = duedateCalendar.get();
c.set(Calendar.YEAR,2017);
duedateCalendar.set(c);

最佳答案

如果您传递的值等于当前值,则设置属性值将是空操作,在本例中显然是:

Calendar c = duedateCalendar.get();
// c is now a copy of the reference held internally by duedateCalendar

c.set(Calendar.YEAR,2017);
// this updates the Calendar object referenced both by c and internally
// by duedateCalendar. Since the YEAR field in Calendar is just a primitive,
// and is not an observable value in the JavaFX sense, nothing is notified
// of the change

duedateCalendar.set(c);
// the value passed to set here is equal (indeed identical) to the value
// held internally by duedateCalendar (since it's an actual copy of the
// same reference). Internally, duedateCalendar will compare the parameter
// to the value it already holds, will see that they are the same, and
// so will take no action (including not notifying listeners)

因此不会触发任何更改事件(实际上没有任何可观察到的更改)。

您可以创建一个代表新日期的新Calendar 并将其设置为:

Calendar c = duedateCalendar.get();
Calendar newDueDate = Calendar.getInstance();
newDueDate.setTime(c.getTime());
newDueDate.set(Calendar.YEAR, 2017);
duedateCalendar.set(newDueDate);

顺便说一句,我强烈建议使用 java.time API (例如 LocalDateLocalDateTime)而不是遗留的 Calendar 类。此 API 中的类在很大程度上是不可变的(因此它们可以更好地与 JavaFX 属性类一起工作),并且具有返回适当类的新实例的功能方法。例如,LocalDate 是不可变的,并且具有 LocalDate.plusYears(...) 等方法返回对新 LocalDate 对象的引用。所以你可以这样做:

// just create a random date sometime in 2016:
Random rng = new Random();
LocalDate random2016Date = LocalDate.of(2016, 1, 1).plusDays(rng.nextInt(365));

// general listener for logging:
ChangeListener<Object> listener = (obs, oldVal, newVal) -> System.out.println(oldVal + " -> " + newVal);


ObjectProperty<LocalDate> date = new SimpleObjectProperty<>(random2016Date);
date.addListener(listener);

// add one year to the current date:
date.set(date.get().plusYears(1));

关于java - 如何修改调用更改监听器的 javafx 对象属性的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37976207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com