JavaFX - TableView 中的不可见数据

标签 java csv javafx tableview scenebuilder

我正在编写一个程序,它从文件(csv)动态读取数据并将其放入TableView中(创建动态行和列)。

我的问题是数据在表中不可见。

我正在使用 IntelliJ IDEA 13.1.4、JavaFX Scene Builder 2.0 和最新的 JavaFX 版本。

感谢您的帮助...

我的代码:

Main.java

package sample;

 import javafx.application.Application; import javafx.fxml.FXMLLoader;
 import javafx.scene.Parent; import javafx.scene.Scene; import
 javafx.stage.Stage;

 public class Main extends Application {

     @Override
     public void start(Stage primaryStage) throws Exception{
         Parent root = FXMLLoader.load(getClass().getResource("Main1.fxml"));
         primaryStage.setTitle("File Converter");
         primaryStage.setScene(new Scene(root, 800, 600));
         primaryStage.show();
     }

     public static void main(String[] args) {
         launch(args);
     } }

Convert.java(这里我从文件中读取数据并将其放入 String[] 列表中)

package sample;

import com.sun.org.apache.xerces.internal.xs.StringList;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.util.Pair;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.sql.SQLException;
import java.util.*;

public class Convert {

    public String delimiterYes;

    public LinkedList<String> fileStrings= new LinkedList<>();

    private final List<String[]> jdata = new LinkedList<>();
    Controller filedata;
    String[] s;
    int colums;
    String[] splitted;

    public List<String[]> insertDataFromFile(String filePath) throws IOException {
        filedata = new Controller();
        FileInputStream file = new FileInputStream(filePath);
        InputStreamReader isr = new InputStreamReader(file, Charset.forName("UTF-8"));
        BufferedReader bufferedReader = new BufferedReader(isr);
        while (bufferedReader.ready()) {
            String lines = bufferedReader.readLine();
            fileStrings.add(lines);
                splitted=(lines.split(";"));
            jdata.add(splitted);
        }
        int l = 0;
        for(String[] str: jdata){
            if(str.length > l){
                l = str.length;
            }
        }System.out.println(l);
        s = fileStrings.get(0).split(";");
        colums = l;
        return jdata;
    }
    public String[] getHeader() {
        return s;
    }

    public int getColums() {
        return colums;
    }
}

Controller .java

package sample;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.FileChooser;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;
import java.util.List;

import javafx.scene.control.Button;
import javafx.scene.control.TableView;

public class Controller {
    public List<String[]> jdata = new LinkedList<>();


    String path;
    @FXML
    private Button tcodeBtn;

    @FXML
    private TableView<String[]> sourceTable=new TableView<String[]>();
    private ObservableList<String[]> srcData;// = FXCollections.observableArrayList();


    @FXML
    private TableView<String> finalTable;
    ObservableList<String> fnlTable;

    @FXML
    private Button moveBtn;

    @FXML
    private Button cnvrtBtn;

    @FXML
    private Button openBtn;

    @FXML
    private Button delteBtn;

    @FXML
    private Button splitBtn;

    @FXML
    private Button addBtn;

    @FXML
    private Button linkBtn;

    @FXML
    private Button saveBtn;

    Convert converter= new Convert();
    @FXML
    void openAction(ActionEvent event) throws IOException {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Open Resource File");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("All Files", "*.*"));
        File selectedFile = fileChooser.showOpenDialog(null);
        if(selectedFile != null){
            sourceTable.getItems().clear();
            sourceTable.getColumns().clear();
            srcInput.setText(selectedFile.getAbsolutePath());
            //converter.delimiter();
            path=selectedFile.getAbsolutePath();
            jdata = converter.insertDataFromFile(path);
            showTable(converter);
            initialize();
        }
    }

    @FXML
    void saveAction(ActionEvent event) throws IOException {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Save Resource File");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("CSV", "*.csv"),
                new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                new FileChooser.ExtensionFilter("Text", "*.txt"));
        File file = fileChooser.showSaveDialog(null);
        if (file != null) {
            String content = "Hello File; Test; Test; Test; 123456";
            Files.write(Paths.get(file.getAbsolutePath()), content.getBytes(), StandardOpenOption.CREATE);
        }
    }

    @FXML
    private TextField srcInput;

    Convert converted = new Convert();
    int clms = converted.getColums();


    public void showTable(Convert cnv) {

        sourceTable.setEditable(true);
        clms = cnv.getColums();

        for (int i = 0; i < clms; i++) {
                TableColumn firstNameCol = new TableColumn("\tC"+(i+1)+" \t");
                firstNameCol.setMinWidth(20);
                firstNameCol.setCellValueFactory(new PropertyValueFactory<String, String>("\tC"+(i+1)+" \t"));
            sourceTable.getColumns().add(firstNameCol);
        }
        srcData = FXCollections.observableList(jdata);
        sourceTable.setItems(srcData);
    }



    @FXML
    void initialize() {
        assert tcodeBtn != null : "fx:id=\"tcodeBtn\" was not injected: check your FXML file 'FXML.fxml'.";
        assert sourceTable != null : "fx:id=\"sourceTable\" was not injected: check your FXML file 'FXML.fxml'.";
        assert finalTable != null : "fx:id=\"finalTable\" was not injected: check your FXML file 'FXML.fxml'.";
        assert srcInput != null : "fx:id=\"srcInput\" was not injected: check your FXML file 'FXML.fxml'.";
        assert moveBtn != null : "fx:id=\"moveBtn\" was not injected: check your FXML file 'FXML.fxml'.";
        assert cnvrtBtn != null : "fx:id=\"cnvrtBtn\" was not injected: check your FXML file 'FXML.fxml'.";
        assert openBtn != null : "fx:id=\"openBtn\" was not injected: check your FXML file 'FXML.fxml'.";
        assert delteBtn != null : "fx:id=\"delteBtn\" was not injected: check your FXML file 'FXML.fxml'.";
        assert splitBtn != null : "fx:id=\"splitBtn\" was not injected: check your FXML file 'FXML.fxml'.";
        assert addBtn != null : "fx:id=\"addBtn\" was not injected: check your FXML file 'FXML.fxml'.";
        assert linkBtn != null : "fx:id=\"linkBtn\" was not injected: check your FXML file 'FXML.fxml'.";
        assert saveBtn != null : "fx:id=\"saveBtn\" was not injected: check your FXML file 'FXML.fxml'.";

    }
}

FXML.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.effect.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>

<AnchorPane prefHeight="600.0" prefWidth="800.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
   <children>
      <Button fx:id="delteBtn" layoutX="32.0" layoutY="272.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" prefHeight="30.0" prefWidth="90.0" text="DELETE" />
      <Button fx:id="addBtn" layoutX="138.0" layoutY="272.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" prefHeight="30.0" prefWidth="90.0" text="ADD" />
      <Button fx:id="moveBtn" layoutX="243.0" layoutY="272.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" prefHeight="30.0" prefWidth="90.0" text="MOVE" />
      <Button fx:id="linkBtn" layoutX="350.0" layoutY="272.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" prefHeight="30.0" prefWidth="90.0" text="LINK" />
      <Button fx:id="splitBtn" layoutX="461.0" layoutY="272.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" prefHeight="30.0" prefWidth="90.0" text="SPLIT" />
      <Button fx:id="tcodeBtn" layoutX="569.0" layoutY="272.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" prefHeight="30.0" prefWidth="90.0" text="TRANSCODE" />
      <Button fx:id="cnvrtBtn" layoutX="679.0" layoutY="272.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" prefHeight="30.0" prefWidth="90.0" text="CONVERT" />
      <Button fx:id="saveBtn" layoutX="684.0" layoutY="551.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" onAction="#saveAction" prefHeight="30.0" prefWidth="90.0" text="SAVE" />
      <TableView fx:id="sourceTable" editable="true" layoutX="17.0" layoutY="65.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="190.0" prefWidth="766.0" />
      <TableView fx:id="finalTable" layoutX="17.0" layoutY="348.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="190.0" prefWidth="766.0" />
      <Button fx:id="openBtn" layoutX="572.0" layoutY="551.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" onAction="#openAction" prefHeight="30.0" prefWidth="90.0" text="OPEN" />
      <TextField fx:id="srcInput" editable="false" layoutX="69.0" layoutY="551.0" prefHeight="30.0" prefWidth="495.0" />
      <TextField editable="false" layoutX="17.0" layoutY="36.0" text="Source File" />
      <TextField editable="false" layoutX="17.0" layoutY="319.0" text="Converted File" />
   </children>
</AnchorPane>

CSV 示例(只需将其另存为 .csv)

TagS;TagN;MonatS;MonatN;Jahr;ME;
Montag;1;Februar;2;2015;Stk;
Dienstag;5;Mai;5;2015;Stk;
Mittwoch;11;April;4;2015;Stk;
Donnerstag;17;Juli;7;2015;Stk;
Freitag;20;August;8;2015;Stk;
Samstag;25;November;11;2015;Stk;
Sonntag;31;Dezember;12;2015;Stk;

-屏幕截图- /image/t3rwA.png

看起来就是这样,数据不可见,但列数和行数是准确的

最佳答案

您的cellValueFactory是错误的。请参阅 PropertyValueFactory 的文档;这将查看您的行数据(String[])并尝试找到 C1\tProperty() 形式的方法,这当然不会存在。

你需要做:

    for (int i = 0; i < clms; i++) {
        TableColumn<String[], String> firstNameCol = new TableColumn<>("\tC"+(i+1)+" \t");
        firstNameCol.setMinWidth(20);
        int index = i ;
        firstNameCol.setCellValueFactory(cellData -> {
            String[] rowData = cellData.getValue();
            if (index >= rowData.length) {
                return new ReadOnlyStringWrapper("");
            } else {
                String cellValue = rowData[index];
                return new ReadOnlyStringWrapper(cellValue);
            }
        });
        sourceTable.getColumns().add(firstNameCol);
    }

关于JavaFX - TableView 中的不可见数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31380913/

相关文章:

java - 简单的 JavaFX 浏览器仅在第一次打开时有效

javascript - 使用js从本地加载CSV文件: no error but no view

python - Pandas 的 read_csv C 引擎有什么方法可以忽略或替换 Unicode 解析错误吗?

java - 填充 ComboBox 后 FXML 场景生成器无效属性

JavaFX MouseDragReleased 事件未发送到 fullDrag 中的目标节点

java - 使用枚举值作为泛型参数实现接口(interface)

java - 如何使用 DynamicJasper 在没有组的情况下在 JasperReports 的页脚处显示每列的总和?

JAVA将数组显示为矩阵并且随机数等于最小值

csv - Cypher 用 python 加载 csv

java - 测试在 TestFX 上通过,但在 headless 模式下未通过