繁体   English   中英

向 JavaFX 中的表添加可观察列表

[英]Adding an Observable List to a Table in JavaFX

我对在 JavaFX 环境中工作还很陌生,我正在尝试制作一个 MVC 管理系统应用程序。 我目前在运行我的应用程序时没有收到任何问题,但是表中没有填充数组列表中的任何对象。 我调用 getCurrentList() 的方式有问题吗? 如果这很明显,我们深表歉意,但我们将不胜感激。

FacultyController.java


import au.edu.uts.ap.javafx.*;

import javafx.fxml.*;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.event.ActionEvent;
import javafx.scene.Parent;
import javafx.scene.Node;
import javafx.scene.control.TableView;
import javafx.scene.control.TableColumn;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.scene.control.TableView.TableViewSelectionModel;
import javafx.scene.control.cell.PropertyValueFactory;
import model.Student;
import javafx.beans.property.*;


public class FacultyController extends Controller<FacultyController> {

    
    public ObservableList<model.Student> studentsL;
    
    private Stage stage;
    private Scene scene;
    private Parent root;    
    
   @FXML
    private TableView<model.Student> studentTable;
   
    @FXML
    private TableColumn<model.Student, String> name;
   
    @FXML
    private TableColumn<model.Student, String> email;

    @FXML
    private TableColumn<model.Student, String> phone;


//Read Student List into Table
@FXML private void initialize(URL url, ResourceBundle resources){

    model.Students studentList = new model.Students();
    studentsL.equals(studentList.getCurrentList());
 
 
    
    name.setCellValueFactory(new PropertyValueFactory<model.Student, String>("name"));
    email.setCellValueFactory(new PropertyValueFactory<model.Student, String>("email")); 
    phone.setCellValueFactory(new PropertyValueFactory<model.Student, String>("phone"));

    studentTable.setItems(studentsL);
   
}

教师.fxml

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Separator?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.cell.PropertyValueFactory?>
<?import javafx.scene.effect.DropShadow?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.VBox?>

<VBox alignment="center" prefHeight="433.0" prefWidth="673.0" spacing="10" styleClass="background" stylesheets="@tmsfx.css" xmlns="http://javafx.com/javafx/17" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller.FacultyController">
   <children>
      <AnchorPane prefHeight="116.0" prefWidth="650.0">
         <children>
            <Label layoutX="23.0" layoutY="14.0" prefHeight="40.0" prefWidth="126.0" style="-fx-text-fill: white; -fx-font-size: 32;" stylesheets="@tmsfx.css" text="Filters" textFill="WHITE" />
            <Label layoutX="38.0" layoutY="69.0" style="-fx-font-size: 14; -fx-text-fill: white;" text="Name:" />
            <TextField layoutX="102.0" layoutY="66.0" />
            <Label layoutX="288.0" layoutY="70.0" style="-fx-text-fill: white; -fx-font-size: 14px;" text="Email:" />
            <TextField layoutX="350.0" layoutY="67.0" />
         </children>
      </AnchorPane>
      <AnchorPane prefHeight="253.0" prefWidth="572.0" stylesheets="@tmsfx.css">
         <children>
            <Separator layoutX="15.0" layoutY="13.0" prefHeight="3.0" prefWidth="617.0" />
            <TableView fx:id="studentTable" items="${controller.student.students}" layoutX="18.0" layoutY="23.0" prefHeight="200.0" prefWidth="617.0" stylesheets="@tmsfx.css">
                <placeholder><Label text="Student list is not listed" /></placeholder>
              <columns>
                <TableColumn fx:id="name" prefWidth="173.0" text="Name">
                    <cellValueFactory> <PropertyValueFactory property="Name" /></cellValueFactory>
                </TableColumn>
                <TableColumn fx:id="email" prefWidth="215.0" text="Email"> 
                    <cellValueFactory><PropertyValueFactory property="Email" /></cellValueFactory> 
                </TableColumn>
                <TableColumn fx:id="phone" minWidth="0.0" prefWidth="176.0" text="Phone"> 
              <cellValueFactory> <PropertyValueFactory property="phone" /></cellValueFactory> 
                </TableColumn>
              </columns>
            </TableView>
            <Separator layoutX="10.0" layoutY="231.0" prefHeight="3.0" prefWidth="625.0" />
         </children>
      </AnchorPane>
      <AnchorPane prefHeight="46.0" prefWidth="580.0">
         <children>
            <Button alignment="TOP_CENTER" cancelButton="true" layoutX="3.0" layoutY="1.0" maxWidth="100.0" minWidth="100.0" mnemonicParsing="false" onAction="#switchToAdd" prefHeight="18.0" prefWidth="60.0" style="-fx-pref-width: 100px; -fx-font-weight: bold; -fx-effect: dropshadow;" stylesheets="@tmsfx.css" text="Add">
               <effect>
                  <DropShadow />
               </effect></Button>
            <Button disable="true" layoutX="108.0" layoutY="1.0" minWidth="-Infinity" mnemonicParsing="false" prefHeight="18.0" prefWidth="85.0" text="Delete">
               <effect>
                  <DropShadow />
               </effect></Button>
            <Button disable="true" layoutX="213.0" layoutY="2.0" mnemonicParsing="false" text="Select">
               <effect>
                  <DropShadow />
               </effect></Button>
            <Button disable="true" layoutX="317.0" layoutY="1.0" mnemonicParsing="false" style="-fx-effect: dropshadow;" stylesheets="@tmsfx.css" text="SLIP">
               <effect>
                  <DropShadow />
               </effect></Button>
            <Button layoutX="422.0" layoutY="1.0" mnemonicParsing="false" prefHeight="23.0" prefWidth="90.0" onAction="#switchToTMS" style="-fx-effect: dropshadow;" text="Report">
               <effect>
                  <DropShadow />
               </effect></Button>
            <Button layoutX="527.0" layoutY="1.0" mnemonicParsing="false" onAction="#switchToMenu" prefHeight="23.0" prefWidth="90.0" style="-fx-effect: dropshadow;" text="Close">
               <effect>
                  <DropShadow />
               </effect>
            </Button>
         </children>
      </AnchorPane>
   </children>
</VBox>

学生.java

package model;


import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ReadOnlyDoubleProperty;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public class Student {
    private StringProperty name;
    private StringProperty email;
    private StringProperty phone;
    private StringProperty address;
    private StringProperty ID;
    private StringProperty type; 
    private IntegerProperty credits;
    private DoubleProperty payPerCredit;
    private DoubleProperty totalFee;
    private DoubleProperty scholarship;
    private DoubleProperty netFee;
    private DoubleProperty deduction;
    private DoubleProperty deductionRate;
    private Faculty faculty;

    public Student(String name, String email, String phone, String address, String ID, String type, int credits, double scholarship, String deductionCode) {
        this.name = new SimpleStringProperty();
        this.name.set(name);
        this.email = new SimpleStringProperty();
        this.email.set(email);
        this.phone = new SimpleStringProperty();
        this.phone.set(phone);
        this.address = new SimpleStringProperty();
        this.address.set(address);
        this.ID = new SimpleStringProperty();
        this.ID.set(ID);
        this.type = new SimpleStringProperty();
        this.type.set(type);
        this.credits = new SimpleIntegerProperty();
        this.credits.set(credits);
        this.payPerCredit = new SimpleDoubleProperty();
        this.payPerCredit.set(500.00);     
        this.totalFee = new SimpleDoubleProperty();
        this.totalFee.bind(this.credits.multiply(this.payPerCredit));
        this.scholarship = new SimpleDoubleProperty();
        this.scholarship.set(scholarship);
        this.deductionRate = new SimpleDoubleProperty();
        this.deductionRate.set(0.10);
        this.deduction = new SimpleDoubleProperty();
        if (deductionCode.equals("2022AUT"))
        this.deduction.bind(this.totalFee.multiply(this.deductionRate));
        else 
        this.deduction.set(0.00);
        this.netFee = new SimpleDoubleProperty();
        this.netFee.bind(this.totalFee.subtract(deduction).subtract(scholarship));
        
    }

    public void updateDetails(String name, String email, String phone, String address, String ID, String type, int credits, double scholarship, String deductionCode){       
        this.name.set(name);    
        this.email.set(email);        
        this.phone.set(phone);     
        this.address.set(address);        
        this.ID.set(ID);    
        this.type.set(type);
        this.credits.set(credits);        
        this.scholarship.set(scholarship);
        if (deductionCode.equals("2022AUT"))
            this.deduction.bind(this.totalFee.multiply(this.deductionRate));
        else 
            this.deduction.set(0.00);
    }
    
    public void setFaculty(Faculty e){
        this.faculty = e;
    }
    
    public Faculty getFaculty(){
        return this.faculty;
    }
    
    public ReadOnlyStringProperty nameProperty() {
        return name;
    }

    public String getName(){
        return name.getValue();
    }
    
    public ReadOnlyStringProperty emailProperty() {
        return email;
    }

    public String getEmail(){
        return email.getValue();
    }
    
    public ReadOnlyStringProperty phoneProperty() {
        return phone;
    }

    public String getPhone(){
        return phone.getValue();
    }
    
    public ReadOnlyStringProperty addressProperty() {
        return address;
    }

    public String getAddress(){
        return address.getValue();
    }
    
    public ReadOnlyStringProperty IDProperty() {
        return ID;
    }

    public String getID(){
        return ID.getValue();
    }
    
    public ReadOnlyStringProperty typeProperty() {
        return type;
    }

    public String getType(){
        return type.getValue();
    }
    
    public IntegerProperty creditsProperty() {
        return credits;
    }
    
    public int getCredits(){
        return credits.get();
    }

    public ReadOnlyDoubleProperty payPerCreditProperty() {
        return payPerCredit;
    }    
    
    public double getPayPerCredit(){
        return payPerCredit.get();
    }
    
    public ReadOnlyDoubleProperty totalFeeProperty() {
        return totalFee;
    }    
    
    public double getTotalFee(){
        return totalFee.get();
    }
    
    public ReadOnlyDoubleProperty netFeeProperty() {
        return netFee;
    }    
    
    public double getNetFee(){
        return netFee.get();
    }
    
    public ReadOnlyDoubleProperty scholarshipProperty() {
        return scholarship;
    }    
    
    public double getScholarship(){
        return scholarship.get();
    }
    
    public ReadOnlyDoubleProperty deductionProperty() {
        return deduction;
    }    
    
    public double getDeduction(){
        return deduction.get();
    }
    
    public ReadOnlyDoubleProperty deductionRateProperty() {
        return deductionRate;
    }    
    
    public double getDeductionRate(){
        return deductionRate.get();
    }
    
    public boolean hasName(String name){
        return getName().toLowerCase().contains(name.toLowerCase().trim());
    } 
    
    public boolean hasEmail(String email){
        return getEmail().toLowerCase().contains(email.toLowerCase().trim());
    }

    public boolean deleteStudent() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

学生.java

package model;


import java.util.ArrayList;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;

public class Students {

    private ObservableList<Student> students;
    private ObservableList<Student> current;

    public Students() {
        current = FXCollections.<Student>observableArrayList();
        students = FXCollections.observableArrayList(
                new Student("Thomas Muller", "thomas.muller@uts.com", "99991111", "3 Byern St. Sydney 2001", "13697480", "Full-Time", 48, 4000, ""),
                new Student("Alice Stefan", "alice.stefan@uts.com", "88881111", "24 Pitt St. Sydney 2001", "14517880", "Part-Time", 24,0, ""),
                new Student("Lucy Lu", "lucy.lu@uts.com", "98981100", "11 Hunter St. Sydney 2100", "13267102", "Full-Time", 48,0, "2022AUT"),
                new Student("Andreas Brehme", "andreas.b@uts.com", "90001222", "91 Sussex St. Sydney 2100", "13678020", "Full-Time", 48,0, ""),
                new Student("Ruddy Voller", "ruddy.v@uts.com", "98980000", "15 Stan St. Sydney 2100", "13972870", "Full-Time", 48,8000, ""),
                new Student("Monica Shwarz", "monica.s@uts.com", "92241188", "155 Jones St. Sydney 2001", "13859610", "Part-Time", 24,0, "2022AUT")
        );
        current.addAll(students);
        students.addListener(new ListChangeListener<Student>() {
            @Override
            public void onChanged(javafx.collections.ListChangeListener.Change<? extends Student> c) {
                current.clear();
                current.addAll(students);
            }
        });
    }

    public void addStudent(Student student) {
        students.add(student);
    }

    public void addStudent(String name, String email, String phone, String address, String ID, String type, int credits, double scholarship, String deductionCode) {
        students.add(new Student(name,email,phone,address,ID,type,credits,scholarship, deductionCode));
    }
    
    public boolean hasStudent(String name) {
        for(Student e:students)
            if(e.hasName(name)&& !name.isEmpty())
                return true;
        return false;
    }
    
    public Student getStudent(String name){
        for(Student p: students)
            if(p.hasName(name))
                return p;
        return null;                        
    }

    public void remove(Student p) {
        this.students.remove(p);
    }

    public void remove(List<Student> selectedItems) {
        this.students.removeAll(selectedItems);
    }

    public void addStudents(List<Student> selectedItems) {
        this.students.addAll(selectedItems);
    }

    public ObservableList<Student> getCurrentList() {
        return this.current;
    }

    public void filterList(String name, String email) {

        List<Student> temp = new ArrayList<>();

        students.forEach((Student p) -> {
            try {
                if ((p.hasName(name)) || (p.hasEmail(email))) {
                    temp.add(p);
                }
            } catch (NumberFormatException e) {
            }
        });

        this.current.clear();
        this.current.addAll(temp);
    }
}

如我所见,您的数据 model 是Students ,您要显示的学生存储在current中。 如果这是正确的,您必须将此列表设置为您的表的项目。

studentTable.setItems(studentList.getCurrentList());

代替

studentTable.setItems(studentsL);

注意:我没有看到studentsL的任何初始化,所以我希望在这一行出现NullPointerExceptionstudentsL.equals(studentList.getCurrentList()); (什么都不做,因为你不存储结果)

编辑

这个最小的Application工作正常。 也许您的 FXML 使用有问题。 我不使用 FXML,所以我没有进一步的想法:(

public final class FacultyController extends Application {

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

    @Override
    public void start(Stage stage) {
        Students model = new Students();
        TableColumn<Student, String> id = new TableColumn<>("ID");
        // id.setCellValueFactory(new PropertyValueFactory<>("id"));
        id.setCellValueFactory(cdf -> cdf.getValue().idProperty());
        TableView<Student> table = new TableView<>();
        table.getColumns().add(id);
        table.setItems(model.getCurrentList());
        Scene scene = new Scene(table);
        stage.setScene(scene);
        stage.show();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM