When I generate a table in JavaFX, the columns are too large and I want to resize them when it appears on my app in order to reduce them. I read those articles on stackOverflow which are usefull but they didn't help me : javafx column in tableview auto fit size ; JavaFX TableColumn resize to fit cell content. Indeed, unlike theme, I have columns in my columns and it doesn't work. For information those columns react as the same way, if we double click on them they resize automatically. I tried to reproduce those solutions like that :
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.util.List;
import java.util.stream.Collectors;
import com.sun.javafx.scene.control.skin.TableViewSkin;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
public class GUIUtils {
private static Method columnToFitMethod;
static {
try {
columnToFitMethod = TableViewSkin.class.getDeclaredMethod("resizeColumnToFitContent",TableColumn.class,int.class);
columnToFitMethod.setAccessible(true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
public static <S> void autoFitTable(TableView<S> tableView) {
tableView.getItems().addListener(new ListChangeListener<Object>() {
@Override
public void onChanged(Change<?> c) {
for (TableColumn column : tableView.getColumns()) {
try {
List<TableColumn<S, ?>> columns = (List<TableColumn<S, ?>>) column.getColumns.stream().collect(Collectors.toList());
for (TableColumn col : columns) {
columnToFitMethod.invoke(tableView.getSkin(), col, -1);
}
columnToFitMethod.invoke(tableView.getSkin(), column, -1);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
});
}
}
During my second iteration for child column, I have :
java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at myPackage.GUIUtils$1.onChanged(GUIUtils.java:37) . . . Caused by: java.lang.NullPointerException at com.sun.javafx.scene.control.skin.TableViewSkin.resizeColumnToFitContent(TableViewSkin.java:257) ... 80 more
Do you have an idea of what can I do ? Thank you for your help