user3717821
user3717821

Reputation: 83

javafx tableview how to get selected data without using class

I am working on a javafx project and i want to get selected data from tableview but i don't want to use class because number of columns are not fixed .So, please help me.

for example:

public static class IdentifiedName { 
    private final int    id;
    private final String name;
    private IdentifiedName(int id, String name) {
        this.id   = id;
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public String getName() {
        return name;
    }
}

This class can only be use for two column table , but in my project client can add column as per his need so please help me to get selected data from tableview

More code here:

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Map;
import javafx.application.Application;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.TableView.TableViewSelectionModel;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;
public class DynamicTable extends Application{
Object newValue;
private ObservableList<ObservableList> data;
private TableView<ObservableList> tableview;


public static void main(String[] args) {
    launch(args);
}

//CONNECTION DATABASE
public void buildData(){
      Connection c ;
      data = FXCollections.observableArrayList();
      try{
        c = DBConnect.connect();
        //SQL FOR SELECTING ALL OF CUSTOMER
        String SQL = "SELECT * from CUSTOMer";
        //ResultSet
        ResultSet rs = c.createStatement().executeQuery(SQL);

        /**********************************
         * TABLE COLUMN ADDED DYNAMICALLY *
         **********************************/
        for(int i=0 ; i<rs.getMetaData().getColumnCount(); i++){
            //We are using non property style for making dynamic table
            final int j = i;                
            TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i+1));
            col.setCellValueFactory(new Callback<CellDataFeatures<ObservableList,String>,ObservableValue<String>>(){                    
                public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) {                                                                                              
                    return new SimpleStringProperty(param.getValue().get(j).toString());                        
                }                    
            });

            tableview.getColumns().addAll(col); 
                 tableview.setEditable(true);
     Callback<TableColumn<Map, String>, TableCell<Map, String>>
        cellFactoryForMap = new Callback<TableColumn<Map, String>,
            TableCell<Map, String>>() {
                @Override
                public TableCell call(TableColumn p) {
                    return new TextFieldTableCell(new StringConverter() {
                        @Override
                        public String toString(Object t) {
                            return t.toString();
                        }
                        @Override
                        public Object fromString(String string) {
                            return string;
                        }                                    
                    });
                }
    };

     if(j!=1)
    col.setCellFactory(cellFactoryForMap);

            System.out.println("Column ["+i+"] ");
        }


        /********************************
         * Data added to ObservableList *
         ********************************/
        while(rs.next()){
            //Iterate Row
            ObservableList<String> row = FXCollections.observableArrayList();
            for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++){
                //Iterate Column
                row.add(rs.getString(i));
            }
            System.out.println("Row [1] added "+row );
            data.add(row);

        }

        //FINALLY ADDED TO TableView
        tableview.setItems(data);
      }catch(Exception e){
          e.printStackTrace();
          System.out.println("Error on Building Data");             
      }
  }


  @Override
  public void start(Stage stage) throws Exception {
    //TableView



    tableview = new TableView();
    buildData();

    //Main Scene
    Scene scene = new Scene(tableview);        

    stage.setScene(scene);
    stage.show();
     tableview.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
@Override
public void changed(ObservableValue observableValue, Object oldValue, Object newValue)     {
    //Check whether item is selected and set value of selected item to Label
    if(tableview.getSelectionModel().getSelectedItem() != null) 
    {    
       TableViewSelectionModel selectionModel = tableview.getSelectionModel();
       ObservableList selectedCells = selectionModel.getSelectedCells();
       TablePosition tablePosition = (TablePosition) selectedCells.get(0);
       Object val = tablePosition.getTableColumn().getCellData(newValue);
       System.out.println("Selected Value" + val);
     }
     }
 });
       TableColumn col_action = new TableColumn<>("Action");
    col_action.setSortable(false);

    col_action.setCellValueFactory(
            new Callback<TableColumn.CellDataFeatures<JavaFXDynTable2.Record, Boolean>, 
            ObservableValue<Boolean>>() {

        @Override
        public ObservableValue<Boolean>         call(TableColumn.CellDataFeatures<JavaFXDynTable2.Record, Boolean> p) {
            return new SimpleBooleanProperty(p.getValue() != null);
        }
    });

    col_action.setCellFactory(
            new Callback<TableColumn<JavaFXDynTable2.Record, Boolean>,     TableCell<JavaFXDynTable2.Record, Boolean>>() {

        @Override
        public TableCell<JavaFXDynTable2.Record, Boolean> call(TableColumn<JavaFXDynTable2.Record, Boolean> p) {
            return new ButtonCell(tableview);
        }

    });
    tableview.getColumns().add(col_action);

  }
   private class ButtonCell extends TableCell<JavaFXDynTable2.Record, Boolean> {
    final CheckBox cellButton = new CheckBox();

    ButtonCell(final TableView tblView){

        cellButton.setOnAction(new EventHandler<ActionEvent>(){

            @Override
            public void handle(ActionEvent t) {

}




        });
    }

    //Display button if the row is not empty
    @Override
    protected void updateItem(Boolean t, boolean empty) {
        super.updateItem(t, empty);
        if(!empty){
            setGraphic(cellButton);
        }
    }
}

} 

Upvotes: 1

Views: 3477

Answers (1)

brian
brian

Reputation: 10969

The problem wasn't errors, but it's good to fix those before posting code, it was the database which I don't have.

I changed it so your table uses ObservableList<String> since that's what you're using and it's best to specify the structure in the table.

This will only run if you have H2 jar in your path or set it as a library in your project. You can remove that part of the code and just use your database.

package dynamictable;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Map;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.TableView.TableViewSelectionModel;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;

public class DynamicTable extends Application{

    private ObservableList<ObservableList<String>> data;
    private TableView<ObservableList<String>> tableview;


    //CONNECTION DATABASE
    public void buildData() {
        data = FXCollections.observableArrayList();
        try {
            DriverManager.registerDriver(new org.h2.Driver());
            Connection c = DriverManager.getConnection("jdbc:h2:mem:");
            //or you can use derby in your jdk folder
            //DriverManager.registerDriver(new org.apache.derby.jdbc.EmbeddedDriver());
            //Connection c = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true");

            Statement stmt = c.createStatement();
            String sql = "CREATE TABLE CUSTOMER (num INTEGER, name VARCHAR(255), address VARCHAR(255))";
            stmt.executeUpdate(sql);
            for (int i = 0; i < 10; i++) {
                sql = "INSERT INTO CUSTOMER VALUES (" + i + ",'1st string in row " + i + "','2nd string in row " + i + "')";
                stmt.executeUpdate(sql);
            }
            //c = DBConnect.connect();
            //SQL FOR SELECTING ALL OF CUSTOMER
            String SQL = "SELECT * from CUSTOMER";
            //ResultSet
            ResultSet rs = c.createStatement().executeQuery(SQL);

            /**
             * ********************************
             * TABLE COLUMN ADDED DYNAMICALLY *
              *********************************
             */
            for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
                //We are using non property style for making dynamic table
                final int j = i;
                TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i + 1));
                col.setCellValueFactory(new Callback<CellDataFeatures<ObservableList<String>, String>, ObservableValue<String>>() {
                    public ObservableValue<String> call(CellDataFeatures<ObservableList<String>, String> param) {
                        return new SimpleStringProperty(param.getValue().get(j));
                    }
                });

                tableview.getColumns().add(col);

                Callback<TableColumn<Map, String>, TableCell<Map, String>> cellFactoryForMap 
                        = new Callback<TableColumn<Map, String>, TableCell<Map, String>>() {
                    @Override
                    public TableCell call(TableColumn p) {
                        return new TextFieldTableCell(new StringConverter() {
                            @Override
                            public String toString(Object t) {
                                return t.toString();
                            }

                            @Override
                            public Object fromString(String string) {
                                return string;
                            }
                        });
                    }
                };

                if (j != 1) {
                    col.setCellFactory(cellFactoryForMap);
                }

                System.out.println("Column [" + i + "] ");
            }

            /**
             * ******************************
             * Data added to ObservableList *
             *******************************
             */
            while (rs.next()) {
                //Iterate Row
                ObservableList<String> row = FXCollections.observableArrayList();
                for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
                    //Iterate Column
                    row.add(rs.getString(i));
                }
                System.out.println("Row [1] added " + row);
                data.add(row);
            }

            rs.close();
            c.close();
            //FINALLY ADDED TO TableView
            tableview.setItems(data);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error on Building Data");
        }
    }

    @Override
    public void start(Stage stage) throws Exception {
    //TableView

        tableview = new TableView();
        tableview.setEditable(true);
        tableview.getSelectionModel().setCellSelectionEnabled(true);
        buildData();

        //Main Scene
        Scene scene = new Scene(tableview);

        stage.setScene(scene);
        stage.show();
        tableview.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
            @Override
            public void changed(ObservableValue observableValue, Object oldValue, Object newValue) {
                //Check whether item is selected and set value of selected item to Label
                if (tableview.getSelectionModel().getSelectedItem() != null) {
                    TableViewSelectionModel selectionModel = tableview.getSelectionModel();
                    ObservableList selectedCells = selectionModel.getSelectedCells();
                    TablePosition tablePosition = (TablePosition) selectedCells.get(0);
                    Object val = tablePosition.getTableColumn().getCellData(newValue);
                    System.out.println("Selected Value " + val);
                    System.out.println("Selected row " + newValue);
                }
            }
        });

        System.out.println("");
        System.out.println("List all data without using table");
        for (ObservableList<String> ol : data){
            System.out.print("row-> ");
            for (String s : ol){
                System.out.print(s+" ");
            }
            System.out.println("");
        }
        System.out.println("");
        System.out.println("Show data at specific location in data");
        System.out.println(" row 6 (index 5), column 2(index 1) -> "+data.get(5).get(1));

        System.out.println("");
        System.out.println("Show data at specific location in table");
        System.out.println(" row 2, col 2 -> "+tableview.getItems().get(1).get(1));
    }

    public static void main(String[] args) {
        launch(args);
    }

}

Upvotes: 1

Related Questions