【问题标题】:Populate TableView using Derby Database使用 Derby 数据库填充 TableView
【发布时间】:2019-10-13 06:42:16
【问题描述】:

这是我第一次使用 Derby 数据库,我无法将信息添加到我的表格视图中。

public class AddController implements Initializable {

    final String DB_URL = "jdbc:derby:StudentDB;";

    @FXML TableView<Student> studentListView;

    @FXML TableColumn stuName;
    @FXML TableColumn stuAge;
    @FXML TableColumn stuMajor;
    @FXML TableColumn stuGPA;


    @FXML ComboBox ageCB;

    @FXML ComboBox majorCB;

    @FXML ComboBox gpaCB;

    ObservableList<Student> studentList;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        studentList = FXCollections.observableArrayList();
        createDB();
        createStudentsDB();
        studentListView.setItems(studentList);
    }

    public void createDB(){
        try
        {
            Connection conn = DriverManager.getConnection("jdbc:derby:StudentDB;create=true");
            conn.close();
            System.out.println("Connection successful");
        }
        catch(Exception ex)
        {
            System.out.println("ERROR: " + ex.getMessage());
        }
    }

    public void createStudentsDB(){
        try{
            Connection conn = DriverManager.getConnection(DB_URL);

            Statement stmt = conn.createStatement();
            stmt.execute("DROP TABLE Student");

            stmt.execute("CREATE TABLE Student (" +
                    "Name CHAR(25), " +
                    "Age INT, " +
                    "Major CHAR(45), " +
                    "GPA DECIMAL, ");


            String sql = "INSERT INTO Student VALUES" +
                    "('Robert', 21, 'Computer Information Systems', 3.8)";
            stmt.executeUpdate(sql);


            String sqlStatement = "SELECT Name, Age, Major, GPA FROM Student";
            ResultSet result = stmt.executeQuery(sqlStatement);
            ObservableList<Student> studentList = FXCollections.observableArrayList();
            while (result.next())
            {
                Student newStudent = new Student();
                newStudent.name = result.getString("Name");
                newStudent.age = result.getInt("Age");
                newStudent.major = result.getString("Major");
                newStudent.gpa = result.getDouble("GPA");

                studentList.add(newStudent);
            }

            stmt.close();
            conn.close();

        }
        catch (Exception ex)
        {
            var msg = ex.getMessage();
            System.out.println(msg);
        }
    }
<TableView fx:id="studentListView" prefWidth="400">
  <columns>
    <TableColumn fx:id="stuName" text="Student" prefWidth="125"/>
    <TableColumn fx:id="stuAge" text="Age" prefWidth="75"/>
    <TableColumn fx:id="stuMajor" text="Major" prefWidth="125"/>
    <TableColumn fx:id="stuGPA" text="GPA" prefWidth="75"/>
  </columns>
</TableView>

我已经在 FXML 中创建了一个 TableView,其中包含我想要的 4 列。我只是不知道如何从数据库中获取信息到TableView

【问题讨论】:

  • 您缺少列的cellValueFactorys。此外,createStudentsDB 中的 studentList 局部变量会影响该字段;从方法中删除新列表的声明/创建。此外,您应该避免允许其他类访问字段,除非该类服务于非常特定的内部目的并且其他类无法访问,即使那样它也是可疑的。考虑声明一个采用 4 个值的构造函数...
  • 你有任何好的教程的链接吗?我仍然无法填充我的表格视图。 @fabian
  • javafx 标签的信息页面有教程参考。另一个更进一步:最好不要吞下异常的所有细节 - 而不是只打印消息,使用 exception.printStacktrace

标签: javafx derby


【解决方案1】:

此代码从 Derby 数据库中读取名为 Parent
的表 我们正在使用 MVC 模型视图控制器模式
我们强烈建议您在使用任何数据库时使用 MVC 概念

 private void ReadFromParent() throws SQLException{


ObservableList<ParentModel> TableData = FXCollections.observableArrayList();
    stmnt = conn.createStatement();
    ResultSet rs = stmnt.executeQuery("SELECT * FROM Parent"); 
    while (rs.next()){// Add data to observableArrayList TableData to select a table ROW

    TableData.add(new ParentModel(rs.getString("PID"),rs.getString("pMonth"),rs.getString("pYear")));
    }
    PropertyValueFactory<ParentModel, String> IDCellValueFactory = new PropertyValueFactory<>("PID");
    colID.setCellValueFactory(IDCellValueFactory);
    PropertyValueFactory<ParentModel, String> DateCellValueFactory = new PropertyValueFactory<>("pMonth");
    colMonth.setCellValueFactory(DateCellValueFactory);
    PropertyValueFactory<ParentModel, String> TypeCellValueFactory = new PropertyValueFactory<>("pYear");
    colYear.setCellValueFactory(TypeCellValueFactory);

    // ================================================================
    // colTxDate are the ID's for the tableview columns
    // sortDate  are the Column Names for the Database TABLE CDBalance
    // ================================================================
    colMonth.setStyle("-fx-alignment: CENTER;");
    colYear.setStyle("-fx-alignment:CENTER;");

    Collections.sort(TableData, (p2, p1)-> p1.getPID().compareToIgnoreCase(p2.getPID()));
    // Line of Code above Sorts Database Columns based on VARIABLE in ParentModel
    // Change p2,p1 to sort Ascending or Descending
    if(TableData.size() < 15) {// Format TableView to display Vertical ScrollBar
        ptable.setPrefWidth(336);// 19 is the off set
    }else {
        ptable.setPrefWidth(355);
    }   ptable.setItems(TableData);
    stmnt.close();  
}

【讨论】:

  • 与问题/解决方案无关:请学习 java 命名约定并遵守它们。这在答案和问题中同样重要:它们是开发人员之间的沟通,越清晰越好。
猜你喜欢
  • 1970-01-01
  • 2018-11-22
  • 2020-06-06
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
  • 2011-12-02
  • 2011-03-22
  • 2016-11-09
相关资源
最近更新 更多