有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

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

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

PersonTableController。阶级

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();
    }
}

还有人。阶级

package com.lil;

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
//import java.util.Comparator;

public class Person
{
  public BooleanProperty selected = new SimpleBooleanProperty();
  public StringProperty firstName;

  public Person(boolean paramBoolean, String paramString)
  {
    this.selected.setValue(Boolean.valueOf(paramBoolean));
    this.firstName = new SimpleStringProperty(paramString);
  }

  public String toString()
  {
    return getFirstName();
  }

  public String getFirstName()
  {
    return (String)this.firstName.get();
  }

  public void setFirstName(String paramString)
  {
    this.firstName.set(paramString);
  }

  public StringProperty firstNameProperty()
  {
    return this.firstName;
  }

  public boolean isSelected()
  {
    return this.selected.get();
  }

  public BooleanProperty selectedProperty()
  {
    return this.selected;
  }

  public void setSelected(boolean paramBoolean)
  {
    this.selected.set(paramBoolean);
  }
}

我希望上面在第一列中用一个未选中的复选框和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);

如果我删除csv inputstream并使用上面的方法填充表格,那么一切都正常工作

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

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


共 (1) 个答案

  1. # 1 楼答案

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

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

    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();
        }
    }
    
    

    现在,我正试图找出如何在每个复选框中添加一个更改侦听器,以便在选中时打印一条状态消息