64 lines
1.3 KiB
Java
64 lines
1.3 KiB
Java
package com.imyeyu.fx.utils;
|
|
|
|
import com.imyeyu.java.ref.Ref;
|
|
import com.imyeyu.utils.Time;
|
|
import javafx.util.StringConverter;
|
|
|
|
import java.text.ParseException;
|
|
import java.time.LocalDate;
|
|
|
|
/**
|
|
* FX 常用字符串转换
|
|
*
|
|
* @author 夜雨
|
|
* @since 2023-02-01 19:51
|
|
*/
|
|
public class StringConverters {
|
|
|
|
/** 日期转换 */
|
|
public static StringConverter<LocalDate> DATE = new StringConverter<>() {
|
|
|
|
@Override
|
|
public String toString(LocalDate date) {
|
|
if (date == null) {
|
|
return null;
|
|
} else {
|
|
return Time.toDate(Time.fromLocalDate(date));
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public LocalDate fromString(String string) {
|
|
try {
|
|
return Time.toLocalDateTime(Time.date.parse(string).getTime()).toLocalDate();
|
|
} catch (ParseException e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
};
|
|
|
|
/**
|
|
* 通用枚举转换,此转换反射枚举项的 name 字段
|
|
*
|
|
* @param enumClass 枚举类
|
|
* @return 转换器
|
|
* @param <T> 枚举类型
|
|
*/
|
|
public static <T extends Enum<T>> StringConverter<T> type(Class<T> enumClass) {
|
|
return new StringConverter<>() {
|
|
|
|
@Override
|
|
public String toString(T object) {
|
|
if (object == null) {
|
|
return "";
|
|
}
|
|
return object.toString();
|
|
}
|
|
|
|
@Override
|
|
public T fromString(String string) {
|
|
return Ref.toType(enumClass, string);
|
|
}
|
|
};
|
|
}
|
|
} |