【发布时间】: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