package com.excellent.archimedes.util;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import org.springframework.util.CollectionUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author zhaoyong
* @Date 2022/10/10
* @Description 表格渲染
*/
public class TableRenderUtil<E> {
/**
* 渲染表格组件
* @param recordClass
* @param columnInfo
* @param dataList
* @param <T>
* @return
*/
public static <T> TableView<T> getTableView( Class<T> recordClass, Map<String,String> columnInfo, List<T> dataList) {
TableView<T> tableView= new TableView<T>();
if (recordClass.getDeclaredFields().length>0) {
for (Field field : recordClass.getDeclaredFields()) {
TableColumn tableColumn = new TableColumn(columnInfo.get(field.getName()));
tableColumn.setMinWidth(200l);
tableColumn.setCellValueFactory(
new PropertyValueFactory<>(field.getName()));//必须和成员属性名称对上才能渲染出来
tableView.getColumns().add(tableColumn);//tableView添加列头
}
// ObservableList<T> data = FXCollections.observableArrayList();
}
ObservableList<T> data = FXCollections.observableArrayList(dataList);
tableView.setItems(data);
return tableView;
}
/**
* 将pojo 的list转换成指定的clazz类型
* @param clazzRecord
* @param pojoClass
* @param pojoList
* @param <T>
* @param <E>
* @return
*/
public static <T, E> List<T> convertPojoToRecord(Class<T> clazzRecord, Class<E> pojoClass, List<E> pojoList) {
List<Method> tRecordSetterMethods = new ArrayList<Method>();
Map<String, Class[]> setterMethodsBinding = new HashMap<String, Class[]>();
Map<String, Class[]> getterMethodsBinding = new HashMap<String, Class[]>();
Method[] methods = clazzRecord.getMethods();
for (Method method : methods) {
if (method.getName().startsWith("set")) {
setterMethodsBinding.put(method.getName().substring(3), method.getParameterTypes());
}
if (method.getName().startsWith("get")) {
getterMethodsBinding.put(method.getName().substring(3), method.getParameterTypes());
}
}
List<T> dataList = new ArrayList<T>();
try {
if (!CollectionUtils.isEmpty(pojoList)) {
for (E pojo : pojoList) {
T record = clazzRecord.newInstance();
for (Map.Entry<String, Class[]> entry : setterMethodsBinding.entrySet()) {
String methodFeature = entry.getKey();
Class[] getter_paramsTypes = getterMethodsBinding.get(methodFeature);
Class[] setter_paramsTypes = entry.getValue();
Method getter = pojo.getClass().getMethod("get" + methodFeature, getter_paramsTypes);
Object getter_value = getter.invoke(pojo, new Object[]{});
Method setter = clazzRecord.getMethod("set" + methodFeature, setter_paramsTypes);
setter.invoke(record, new Object[]{getter_value});
}
dataList.add(record);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
}