2

when i want to add a data to tableview in javafx i receive this error

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

class User

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

and Function data :

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;
}

in controller class :

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





        }
0

1 Answer 1

5

You can't directly cast the ArrayList object to observableList, rather you need to use FXCollections.observableArrayList() as shown in the below code & set that list to your dgv_user object.

ObservableList<User> observableArrayList = 
           FXCollections.observableArrayList(u.afficher_user());
dgv_user.setItems(observableArrayList);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.