Java 从CSV读取以填充包含复选框和字符串的tableview

Java 从CSV读取以填充包含复选框和字符串的tableview,java,javafx,inputstream,desktop-application,Java,Javafx,Inputstream,Desktop Application,我有一个JavaFX桌面应用程序,我正在尝试更新/重新创建,我在读取csv和填充包含复选框列和字符串列的tableview时遇到问题 在使用上面的布尔值(false)和csv文件中字符串的第二部分创建之前,我尝试在第91-92行设置列行的布尔值,但这会导致错误:“无法将BooleanProperty转换为boolean” 我还尝试通过将其添加到第1列的csv中来设置false,即: 虚假的;“NameString1”(换行符) 虚假的;“NameString2”等这将导致程序运行,但列表为空 P

我有一个JavaFX桌面应用程序,我正在尝试更新/重新创建,我在读取csv和填充包含复选框列和字符串列的tableview时遇到问题

在使用上面的布尔值(false)和csv文件中字符串的第二部分创建之前,我尝试在第91-92行设置列行的布尔值,但这会导致错误:“无法将BooleanProperty转换为boolean”

我还尝试通过将其添加到第1列的csv中来设置false,即:

虚假的;“NameString1”(换行符) 虚假的;“NameString2”等这将导致程序运行,但列表为空

PersonTableController.class

package com.lil;

import com.lil.Person;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.SingleSelectionModel;
import javafx.scene.text.Text;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import java.util.ArrayList;
import java.util.List;
import java.util.Comparator;
import java.util.Collections;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;

/**
 * View-Controller for the person table.
 */
public class PersonTableController {
    @FXML
    Button generate;
    @FXML
    Text status;
    @FXML
    TextField textVorname;
    @FXML
    TextField textNachname;
    @FXML
    TextField textUsergroup;
    @FXML
    TextField adname;
    @FXML
    CheckBox checkbox;
    @FXML
    CheckBox checkbox2;
    //@FXML
    //CheckBox selected;
    @FXML
    public TextField filterField;
    @FXML
    public TableView<Person> personTable = new TableView<Person>();
    @FXML
    public TableColumn<Person, Boolean> colSelected;
    @FXML
    public TableColumn<Person, String> colName;

    private BufferedReader br;
    private InputStream importPath;
    /**
     * Just add some sample data in the constructor.
     */

    public ObservableList<Person> myItems = FXCollections.observableArrayList();

    // IMPORT GROUPS FUNCTION
    private ObservableList<Person> importGroups()
    {
      this.importPath = getClass().getResourceAsStream("/input/groups.csv");

      String line = "";

      List<Person> groups = new ArrayList();

      this.br = new BufferedReader(new InputStreamReader(this.importPath));
      ObservableList<Person> observableList;
      try
      {
        while ((line = this.br.readLine()) != null) {
          if (!line.startsWith("Benutzergruppen_ID"))
          {
            String[] parts = line.split(";");
            //BooleanProperty b = new SimpleBooleanProperty(false);
            //boolean r = Boolean.FALSE;
            //Person person = new Person(r, parts[0]);
            Person person = new Person(parts[0], parts[1]);
            groups.add(person);
          }
        }
        observableList = FXCollections.observableList(groups);
      }
      catch (IOException e)
      {
        observableList = FXCollections.observableList(groups);
        System.out.println("IO Exception while reading groups");
      }
      return observableList;
    }
    // IMPORT GROUPS FUNCTION END
    /**
     * Initializes the controller class. This method is automatically called
     * after the fxml file has been loaded.
     * 
     * Initializes the table columns and sets up sorting and filtering.
     */

    @FXML
    public void initialize() {

        // We need the TableView to be editable in order to allow each CheckBox
        personTable.setEditable(true);

        // Bind the columns with our model's properties
        colSelected.setCellValueFactory(f -> f.getValue().selectedProperty());
        colName.setCellValueFactory(f -> f.getValue().firstNameProperty());

        // Set the CellFactory to use a CheckBoxTableCell
        colSelected.setCellFactory(param -> {
            return new CheckBoxTableCell<Person, Boolean>();
        });

        // Add our columns to the TableView
        personTable.getColumns().addAll(colSelected, colName);

        // Set our items to the TableView
        // personTable.setItems(myItems);
        // set Groups from CSV
        personTable.setItems(importGroups());

        // 1. Wrap the ObservableList in a FilteredList (initially display all data).
        FilteredList<Person> filteredData = new FilteredList<>(myItems, p -> true);

        // 2. Set the filter Predicate whenever the filter changes.
        filterField.textProperty().addListener((observable, oldValue, newValue) -> {
            filteredData.setPredicate(person -> {
                // If filter text is empty, display all persons.
                if (newValue == null || newValue.isEmpty()) {
                    return true;
                }

                // Compare first name and last name of every person with filter text.
                String lowerCaseFilter = newValue.toLowerCase();

                if (person.getFirstName().toLowerCase().indexOf(lowerCaseFilter) != -1) {
                    return true; // Filter matches first name.
                }
                return false; // Does not match.
            });
        });

        // 3. Wrap the FilteredList in a SortedList. 
        SortedList<Person> sortedData = new SortedList<>(filteredData);

        // 4. Bind the SortedList comparator to the TableView comparator.
        //    Otherwise, sorting the TableView would have no effect.
        sortedData.comparatorProperty().bind(personTable.comparatorProperty());

        // 5. Add sorted (and filtered) data to the table.
        personTable.setItems(sortedData);
    }

    public void generateImpex() {
        Alert warning = new Alert(AlertType.WARNING, "Generating Impex!", ButtonType.YES, ButtonType.CANCEL);
        warning.showAndWait();
    }
}

我希望上面在第一列中用一个未选中的复选框和csv中的相关名称字符串填充tableView

它应该像下面的例子一样工作,除了在csv内设置初始值false不是一个要求:


    /**
     * Just add some sample data in the constructor.
     */

    public ObservableList<Person> myItems = FXCollections.observableArrayList();

    public PersonTableController() {
        myItems.add(new Person(false, "Hans"));
        myItems.add(new Person(false, "Ruth"));
        myItems.add(new Person(false, "Heinz"));
        myItems.add(new Person(false, "Cornelia"));
        myItems.add(new Person(false, "Werner"));
        myItems.add(new Person(false, "Lydia"));
        myItems.add(new Person(false, "Anna"));
        myItems.add(new Person(false, "Stefan"));
        myItems.add(new Person(false, "Martin"));
        myItems.add(new Person(false, "Joni"));
        myItems.add(new Person(false, "Chachi"));
        myItems.add(new Person(false, "Phillip"));
        myItems.add(new Person(false, "Susan"));
        myItems.add(new Person(false, "Joan"));
    }

    /**
     * Initializes the controller class. This method is automatically called
     * after the fxml file has been loaded.
     * 
     * Initializes the table columns and sets up sorting and filtering.
     */
    @FXML
    public void initialize() {

        // We need the TableView to be editable in order to allow each CheckBox to be selectable
        personTable.setEditable(true);

        // Bind the columns with our model's properties
        colSelected.setCellValueFactory(f -> f.getValue().selectedProperty());
        colName.setCellValueFactory(f -> f.getValue().firstNameProperty());

        // Set the CellFactory to use a CheckBoxTableCell
        colSelected.setCellFactory(param -> {
            return new CheckBoxTableCell<Person, Boolean>();
        });

        // Add our columns to the TableView
        personTable.getColumns().addAll(colSelected, colName);

        // Set our items to the TableView
        personTable.setItems(myItems);

/**
*只需在构造函数中添加一些示例数据。
*/
公共ObservableList myItems=FXCollections.observableArrayList();
公共PersonTableController(){
myItems.add(新的人(假,Hans));
myItems.add(新的人(假,“Ruth”);
myItems.add(新的人(假,“Heinz”);
myItems.add(新人物(假,“Cornelia”);
myItems.add(新的人(假,“Werner”);
myItems.add(新人物(假,“Lydia”);
myItems.add(新的人(假,“安娜”);
myItems.add(新的人(假,“Stefan”);
myItems.add(新人物(假,“马丁”);
myItems.add(新的人(假,“Joni”);
myItems.add(新的人(假,“Chachi”);
myItems.add(新人物(假,“Phillip”);
myItems.add(新人物(false,“Susan”);
myItems.add(新人物(假,“琼”);
}
/**
*初始化控制器类。此方法将自动调用
*加载fxml文件后。
* 
*初始化表列并设置排序和筛选。
*/
@FXML
公共无效初始化(){
//我们需要TableView是可编辑的,以便允许每个复选框都是可选择的
personTable.setEditable(true);
//用模型的属性绑定列
colSelected.setCellValueFactory(f->f.getValue().selectedProperty());
colName.setCellValueFactory(f->f.getValue().firstNameProperty());
//将CellFactory设置为使用CheckBoxTableCell
colSelected.setCellFactory(参数->{
返回新的CheckBoxTableCell();
});
//将列添加到TableView
personTable.getColumns().addAll(colSelected,colName);
//将项目设置为TableView
personTable.setItems(myItems);
如果我删除csv inputstream并使用上面的方法填充表格,那么一切都正常工作

有什么想法吗?最好在csv中添加'false'还是修复BooleanProperty>boolean问题?我已经阅读并测试了一些东西,如.booleanValue(),.getValue()


非常感谢所有人和这个伟大的社区!!

错误是我试图从一个我不应该的目录编译控制器。我现在已经让csv读取工作和一个全选复选框工作。目前我正在处理表列复选框的侦听器,以便显示关于哪个组h的状态消息已选定的对象及其布尔值

好的,我能让它像这样工作:

package com.lil;

import com.lil.Person;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.SingleSelectionModel;
import javafx.scene.text.Text;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import java.util.ArrayList;
import java.util.List;
import java.util.Comparator;
import java.util.Collections;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;

/**
 * View-Controller for the person table.
 */
public class PersonTableController {
    @FXML
    Button generate;
    @FXML
    Text status;
    @FXML
    TextField textVorname;
    @FXML
    TextField textNachname;
    @FXML
    TextField textUsergroup;
    @FXML
    TextField adname;
    @FXML
    CheckBox checkbox;
    @FXML
    CheckBox checkbox2;
    //@FXML
    //CheckBox selected;
    @FXML
    public TextField filterField;
    @FXML
    public TableView<Person> personTable = new TableView<Person>();
    @FXML
    public TableColumn<Person, Boolean> colSelected;
    @FXML
    public TableColumn<Person, String> colName;

    private BufferedReader br;
    private InputStream importPath;
    /**
     * Just add some sample data in the constructor.
     */

    public ObservableList<Person> myItems = FXCollections.observableArrayList();

    // IMPORT GROUPS FUNCTION
    private ObservableList<Person> importGroups()
    {
      this.importPath = getClass().getResourceAsStream("/input/groups.csv");

      String line = "";

      this.br = new BufferedReader(new InputStreamReader(this.importPath));
      ObservableList<Person> observableList;
      try
      {
        while ((line = this.br.readLine()) != null) {
          if (!line.startsWith("Benutzergruppen_ID"))
          {
            String[] parts = line.split(";");
            myItems.add(new Person(false, parts[1]));
          }
        }
        observableList = FXCollections.observableList(myItems);
      }
      catch (IOException e)
      {
        observableList = FXCollections.observableList(myItems);
        System.out.println("IO Exception while reading myItems");
      }
      return observableList;
    }
    // IMPORT GROUPS FUNCTION END
    /**
     * Initializes the controller class. This method is automatically called
     * after the fxml file has been loaded.
     * 
     * Initializes the table columns and sets up sorting and filtering.
     */

    @FXML
    public void initialize() {

        // We need the TableView to be editable in order to allow each CheckBox
        personTable.setEditable(true);

        // Bind the columns with our model's properties
        colSelected.setCellValueFactory(f -> f.getValue().selectedProperty());
        colName.setCellValueFactory(f -> f.getValue().firstNameProperty());

        // Set the CellFactory to use a CheckBoxTableCell
        colSelected.setCellFactory(param -> {
            return new CheckBoxTableCell<Person, Boolean>();
        });

        // Add our columns to the TableView
        personTable.getColumns().addAll(colSelected, colName);

        // Set our items to the TableView
        // personTable.setItems(myItems);
        // set Groups from CSV
        personTable.setItems(importGroups());

        // 1. Wrap the ObservableList in a FilteredList (initially display all data).
        FilteredList<Person> filteredData = new FilteredList<>(myItems, p -> true);

        // 2. Set the filter Predicate whenever the filter changes.
        filterField.textProperty().addListener((observable, oldValue, newValue) -> {
            filteredData.setPredicate(person -> {
                // If filter text is empty, display all persons.
                if (newValue == null || newValue.isEmpty()) {
                    return true;
                }

                // Compare first name and last name of every person with filter text.
                String lowerCaseFilter = newValue.toLowerCase();

                if (person.getFirstName().toLowerCase().indexOf(lowerCaseFilter) != -1) {
                    return true; // Filter matches first name.
                }
                return false; // Does not match.
            });
        });

        // 3. Wrap the FilteredList in a SortedList. 
        SortedList<Person> sortedData = new SortedList<>(filteredData);

        // 4. Bind the SortedList comparator to the TableView comparator.
        //    Otherwise, sorting the TableView would have no effect.
        sortedData.comparatorProperty().bind(personTable.comparatorProperty());

        // 5. Add sorted (and filtered) data to the table.
        personTable.setItems(sortedData);
    }

    public void generateImpex() {
        Alert warning = new Alert(AlertType.WARNING, "Generating Impex!", ButtonType.YES, ButtonType.CANCEL);
        warning.showAndWait();
    }
}

package com.lil;
导入com.lil.Person;
导入javafx.collections.FXCollections;
导入javafx.collections.ObservableList;
导入javafx.collections.transformation.FilteredList;
导入javafx.collections.transformation.SortedList;
导入javafx.fxml.fxml;
导入javafx.scene.control.TableColumn;
导入javafx.scene.control.TableView;
导入javafx.scene.control.SingleSelectionModel;
导入javafx.scene.text.text;
导入javafx.scene.control.TextField;
导入javafx.scene.control.cell.CheckBoxTableCell;
导入javafx.scene.control.Button;
导入javafx.scene.control.ButtonType;
导入javafx.scene.control.CheckBox;
导入javafx.scene.control.Alert;
导入javafx.scene.control.Alert.AlertType;
导入javafx.beans.property.BooleanProperty;
导入javafx.beans.property.SimpleBoleAnProperty;
导入javafx.scene.control.cell.PropertyValueFactory;
导入javafx.beans.value.ChangeListener;
导入javafx.beans.value.observeValue;
导入java.util.ArrayList;
导入java.util.List;
导入java.util.Comparator;
导入java.util.Collections;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.PrintStream;
/**
*查看person表的控制器。
*/
公共类PersonTableController{
@FXML
按钮生成;
@FXML
文本状态;
@FXML
TextField textforname;
@FXML
TextField textNachname;
@FXML
TextField textUsergroup;
@FXML
TextField-adname;
@FXML
复选框;
@FXML
复选框2;
//@FXML
//选中复选框;
@FXML
公共文本字段过滤器字段;
@FXML
public TableView personTable=新建TableView();
@FXML
选择公共表格;
@FXML
公共表列colName;
专用缓冲读取程序br;
私有输入流入口路径;
/**
*只需在构造函数中添加一些示例数据。
*/
公共ObservableList myItems=FXCollections.observableArrayList();
//导入组功能
私有可观察列表导入组()
{
this.importPath=getClass().getResourceAsStream(“/input/groups.csv”);
字符串行=”;
this.br=新的BufferedReader(新的InputStreamReader(this.importPath));
观察者观察者;
尝试
{
而((line=this.br.readLine())!=null){
如果(!line.startsWith(“Benutzergruppen_ID
package com.lil;

import com.lil.Person;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.SingleSelectionModel;
import javafx.scene.text.Text;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import java.util.ArrayList;
import java.util.List;
import java.util.Comparator;
import java.util.Collections;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;

/**
 * View-Controller for the person table.
 */
public class PersonTableController {
    @FXML
    Button generate;
    @FXML
    Text status;
    @FXML
    TextField textVorname;
    @FXML
    TextField textNachname;
    @FXML
    TextField textUsergroup;
    @FXML
    TextField adname;
    @FXML
    CheckBox checkbox;
    @FXML
    CheckBox checkbox2;
    //@FXML
    //CheckBox selected;
    @FXML
    public TextField filterField;
    @FXML
    public TableView<Person> personTable = new TableView<Person>();
    @FXML
    public TableColumn<Person, Boolean> colSelected;
    @FXML
    public TableColumn<Person, String> colName;

    private BufferedReader br;
    private InputStream importPath;
    /**
     * Just add some sample data in the constructor.
     */

    public ObservableList<Person> myItems = FXCollections.observableArrayList();

    // IMPORT GROUPS FUNCTION
    private ObservableList<Person> importGroups()
    {
      this.importPath = getClass().getResourceAsStream("/input/groups.csv");

      String line = "";

      this.br = new BufferedReader(new InputStreamReader(this.importPath));
      ObservableList<Person> observableList;
      try
      {
        while ((line = this.br.readLine()) != null) {
          if (!line.startsWith("Benutzergruppen_ID"))
          {
            String[] parts = line.split(";");
            myItems.add(new Person(false, parts[1]));
          }
        }
        observableList = FXCollections.observableList(myItems);
      }
      catch (IOException e)
      {
        observableList = FXCollections.observableList(myItems);
        System.out.println("IO Exception while reading myItems");
      }
      return observableList;
    }
    // IMPORT GROUPS FUNCTION END
    /**
     * Initializes the controller class. This method is automatically called
     * after the fxml file has been loaded.
     * 
     * Initializes the table columns and sets up sorting and filtering.
     */

    @FXML
    public void initialize() {

        // We need the TableView to be editable in order to allow each CheckBox
        personTable.setEditable(true);

        // Bind the columns with our model's properties
        colSelected.setCellValueFactory(f -> f.getValue().selectedProperty());
        colName.setCellValueFactory(f -> f.getValue().firstNameProperty());

        // Set the CellFactory to use a CheckBoxTableCell
        colSelected.setCellFactory(param -> {
            return new CheckBoxTableCell<Person, Boolean>();
        });

        // Add our columns to the TableView
        personTable.getColumns().addAll(colSelected, colName);

        // Set our items to the TableView
        // personTable.setItems(myItems);
        // set Groups from CSV
        personTable.setItems(importGroups());

        // 1. Wrap the ObservableList in a FilteredList (initially display all data).
        FilteredList<Person> filteredData = new FilteredList<>(myItems, p -> true);

        // 2. Set the filter Predicate whenever the filter changes.
        filterField.textProperty().addListener((observable, oldValue, newValue) -> {
            filteredData.setPredicate(person -> {
                // If filter text is empty, display all persons.
                if (newValue == null || newValue.isEmpty()) {
                    return true;
                }

                // Compare first name and last name of every person with filter text.
                String lowerCaseFilter = newValue.toLowerCase();

                if (person.getFirstName().toLowerCase().indexOf(lowerCaseFilter) != -1) {
                    return true; // Filter matches first name.
                }
                return false; // Does not match.
            });
        });

        // 3. Wrap the FilteredList in a SortedList. 
        SortedList<Person> sortedData = new SortedList<>(filteredData);

        // 4. Bind the SortedList comparator to the TableView comparator.
        //    Otherwise, sorting the TableView would have no effect.
        sortedData.comparatorProperty().bind(personTable.comparatorProperty());

        // 5. Add sorted (and filtered) data to the table.
        personTable.setItems(sortedData);
    }

    public void generateImpex() {
        Alert warning = new Alert(AlertType.WARNING, "Generating Impex!", ButtonType.YES, ButtonType.CANCEL);
        warning.showAndWait();
    }
}