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

时间:2017-04-01 21:34:12

标签: java javafx tableview

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

  

java.lang.ClassCastException:java.util.ArrayList无法强制转换为   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;
}
控制器类中的

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





        }

1 个答案:

答案 0 :(得分:2)

您无法直接将ArrayList对象投射到observableList,而是需要使用FXCollections.observableArrayList(),如下面的代码&amp;将list设置为dgv_user对象。

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