gpt4 book ai didi

java.lang.ClassCastException : java. util.ArrayList 无法转换为 javafx.collections.ObservableList

转载 作者:行者123 更新时间:2023-11-30 02:35:43 28 4
gpt4 key购买 nike

当我想在 javafx 中向 tableview 添加数据时,我收到此错误

java.lang.ClassCastException: java.util.ArrayList cannot be cast to javafx.collections.ObservableList

用户类

public class User {
private int id;
private String nom;
private String prenom;
private String cin;
private String tel;
private String adresse;
private String dn;

和函数数据:

public ArrayList afficher_user() throws SQLException{    
ArrayList<User> data = new ArrayList<>();
Connection conn=null;
try {
Class.forName(Driver);
conn = DriverManager.getConnection(URL,"root","");
String sql ="select * from utilisateur";
PreparedStatement Stmt = conn.prepareStatement(sql);
ResultSet rs = Stmt.executeQuery(sql);
while(rs.next()){
User us = new User();
us.setId(rs.getInt("id"));
us.setNom(rs.getString("nom"));
us.setPrenom(rs.getString("prenom"));
us.setCin(rs.getString("cin"));
us.setAdresse(rs.getString("adresse"));
us.setTel(rs.getString("tel"));
us.setDn(rs.getString("dn"));
data.add(us);
}
rs.close();
conn.close();
} catch (ClassNotFoundException ex) {
System.err.println(ex.getMessage());
}
return data;
}

在 Controller 类中:

private TableView<User> dgv_user;
@FXML
private TableColumn<User,String> id;
private TableColumn<User, String> nom;
private TableColumn<User, String> prenom;
private TableColumn<User, String> cin;
private TableColumn<User, String> dn;
private TableColumn<User, String> tel;
private TableColumn<User,String> adresse;


public void creer_user(ActionEvent event) throws SQLException {

User u=new User();
System.out.println(u.afficher_user());
dgv_user.setItems((ObservableList<User>) u.afficher_user());





}

最佳答案

您不能直接将 ArrayList 对象转换为 observableList,而是需要使用 FXCollections.observableArrayList(),如下面的代码并将该 list 设置为您的 dgv_user 对象。

ObservableList<User> observableArrayList = 
FXCollections.observableArrayList(u.afficher_user());
dgv_user.setItems(observableArrayList);

关于java.lang.ClassCastException : java. util.ArrayList 无法转换为 javafx.collections.ObservableList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43162261/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com