I would strongly recommend reorganizing your data so that you have a class with two properties, one of which is an element from your first list, and the other of which is the corresponding element from your second list. Then you can make a list of objects of this class and come down to the usual case.
eg. suppose you have
Then define
public class MyDataType { private final int intValue ; private final String stringValue ; public MyDataType(int intValue, String stringValue) { this.intValue = intValue ; this.stringValue = stringValue ; } public int getIntValue() { return intValue ; } public String getStringValue() { return stringValue ; } }
Now you can do
TableView<MyDataType> table = new TableView<>(); for (int i = 0; i < intList.size() && i < stringList.size(); i++) { table.getItems().add(new MyDataType(intList.get(i), stringList.get(i))); }
and define the columns in the usual way.
If you really cannot do this data conversion for any reason, then you can consider the table type as an integer, with the value for each row being an index in two lists. Fill the table with the values 0, 1,... to the size of the lists. It looks like this:
import java.util.Arrays; import java.util.List; import javafx.application.Application; import javafx.beans.property.ReadOnlyIntegerWrapper; import javafx.beans.property.ReadOnlyStringWrapper; import javafx.scene.Scene; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class TableViewByColumns extends Application { @Override public void start(Stage primaryStage) { List<Integer> intValues = Arrays.asList(1, 2, 3, 4, 5); List<String> stringValues = Arrays.asList("One", "Two", "Three", "Four", "Five"); TableView<Integer> table = new TableView<>(); for (int i = 0; i < intValues.size() && i < stringValues.size(); i++) { table.getItems().add(i); } TableColumn<Integer, Number> intColumn = new TableColumn<>("Value"); intColumn.setCellValueFactory(cellData -> { Integer rowIndex = cellData.getValue(); return new ReadOnlyIntegerWrapper(intValues.get(rowIndex)); }); TableColumn<Integer, String> nameColumn = new TableColumn<>("Name"); nameColumn.setCellValueFactory(cellData -> { Integer rowIndex = cellData.getValue(); return new ReadOnlyStringWrapper(stringValues.get(rowIndex)); }); table.getColumns().add(intColumn); table.getColumns().add(nameColumn); primaryStage.setScene(new Scene(new BorderPane(table), 600, 600)); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
source share