javafx tableview get selected data from ObservableList
- by user3717821
i am working on a javafx project and i need your help . while i am trying to get selected data from table i can get selected data from normal cell but can't get data from ObservableList inside tableview.
code for my database:
-- phpMyAdmin SQL Dump
-- version 4.0.4
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jun 10, 2014 at 06:20 AM
-- Server version: 5.1.33-community
-- PHP Version: 5.4.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `test`
--
-- --------------------------------------------------------
--
-- Table structure for table `customer`
--
CREATE TABLE IF NOT EXISTS `customer` (
`col0` int(11) NOT NULL,
`col1` varchar(255) DEFAULT NULL,
`col2` int(11) DEFAULT NULL,
PRIMARY KEY (`col0`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `customer`
--
INSERT INTO `customer` (`col0`, `col1`, `col2`) VALUES
(12, 'adasdasd', 231),
(22, 'adasdasd', 231),
(212, 'adasdasd', 231);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
my javafx codes:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import javafx.application.Application;
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.Button;
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.ChoiceBoxTableCell;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;
class DBConnector {
private static Connection conn;
private static String url = "jdbc:mysql://localhost/test";
private static String user = "root";
private static String pass = "root";
public static Connection connect() throws SQLException{
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
}catch(ClassNotFoundException cnfe){
System.err.println("Error: "+cnfe.getMessage());
}catch(InstantiationException ie){
System.err.println("Error: "+ie.getMessage());
}catch(IllegalAccessException iae){
System.err.println("Error: "+iae.getMessage());
}
conn = DriverManager.getConnection(url,user,pass);
return conn;
}
public static Connection getConnection() throws SQLException, ClassNotFoundException{
if(conn !=null && !conn.isClosed())
return conn;
connect();
return conn;
}
}
public class DynamicTable extends Application{
Object newValue;
//TABLE VIEW AND DATA
private ObservableList<ObservableList> data;
private TableView<ObservableList> tableview;
//MAIN EXECUTOR
public static void main(String[] args) {
launch(args);
}
//CONNECTION DATABASE
public void buildData(){
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;
}
});
}
};
Connection c ;
data = FXCollections.observableArrayList();
try{
c = DBConnector.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));
if(j==1){
final ObservableList<String> logLevelList = FXCollections.observableArrayList("FATAL", "ERROR", "WARN", "INFO", "INOUT", "DEBUG");
col.setCellFactory(ChoiceBoxTableCell.forTableColumn(logLevelList));
tableview.getColumns().addAll(col);
}
else{
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);
}
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
Button showDataButton = new Button("Add");
showDataButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
ObservableList<String> row = FXCollections.observableArrayList();
for(int i=1 ; i<=3; i++){
//Iterate Column
row.add("asdasd");
}
data.add(row);
//FINALLY ADDED TO TableView
tableview.setItems(data);
}
});
tableview = new TableView();
buildData();
//Main Scene
BorderPane root = new BorderPane();
root.setCenter(tableview);
root.setBottom(showDataButton);
Scene scene = new Scene(root,500,500);
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);
}
}
});
}
}
please help me..