You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JFXtras CalendarPicker MouseEvent行为异常,多选日期与ListView同步问题求助

解决JFXtras CalendarPicker多日期选择与ListView同步问题

问题根源

你当前的实现存在三个核心问题:

  • 误用getCalendar()方法:在MULTIPLE模式下,CalendarPicker的选中日期存储在selectedCalendars(ObservableSet)中,getCalendar()仅适用于单选择模式,无法正确获取多选中的状态变化。
  • 依赖鼠标事件不可靠:CalendarPicker内部会先处理日期按钮的选中/取消状态,再触发鼠标事件,导致你获取的日期状态与实际选中状态不同步,重复点击时的事件触发逻辑和组件内部状态更新顺序不匹配。
  • 日期格式化错误:SimpleDateFormat的mm代表分钟,月份应该用MM,否则会把月份解析成分钟值。

正确实现方案

直接监听CalendarPicker的selectedCalendars集合变化,这是组件原生的多选中状态通知机制,能保证状态同步:

步骤1:FXML配置(保持原有配置即可)

<CalendarPicker fx:id="calendarpicker" mode="MULTIPLE" />

步骤2:重写Controller逻辑

import javafx.collections.SetChangeListener;
import javafx.fxml.FXML;
import javafx.scene.control.ListView;
import jfxtras.scene.control.CalendarPicker;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class YourController {
    @FXML
    private CalendarPicker calendarpicker;
    @FXML
    private ListView<String> listview;

    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    public void initialize() {
        // 监听选中日期集合的添加/移除操作
        calendarpicker.selectedCalendarsProperty().addListener((SetChangeListener<Calendar>) change -> {
            Calendar changedCalendar = change.getElementAdded() != null ? change.getElementAdded() : change.getElementRemoved();
            String formattedDate = dateFormat.format(changedCalendar.getTime());

            if (change.wasAdded()) {
                // 日期被选中,添加到ListView
                if (!listview.getItems().contains(formattedDate)) {
                    listview.getItems().add(formattedDate);
                }
            } else if (change.wasRemoved()) {
                // 日期被取消选中,从ListView移除
                listview.getItems().remove(formattedDate);
            }
        });
    }
}

关键说明

  • selectedCalendarsProperty()返回ObservableSet,通过SetChangeListener可以精确捕获每一次添加/移除选中日期的操作,无需手动判断状态。
  • 修正了SimpleDateFormat的格式符,MM表示两位月份,避免日期显示错误。
  • 移除了不可靠的鼠标事件监听,直接依赖组件原生的状态通知机制,完全匹配CalendarPicker的多选中交互逻辑(点击一次选中、再次点击取消)。

内容的提问来源于stack exchange,提问作者Thend

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 22:13:10