javafx tableview从ObservableList获取所选数据
我正在做一个javafx项目,我需要你的帮助。当我试图从表中获取所选数据时,我可以从普通单元格中获取所选数据,但无法从tableview中的ObservableList中获取数据 我的数据库代码:javafx tableview从ObservableList获取所选数据,java,javafx,javafx-2,javafx-8,Java,Javafx,Javafx 2,Javafx 8,我正在做一个javafx项目,我需要你的帮助。当我试图从表中获取所选数据时,我可以从普通单元格中获取所选数据,但无法从tableview中的ObservableList中获取数据 我的数据库代码: -- phpMyAdmin SQL Dump -- version 4.0.4 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jun 10, 2014 at 06:20 AM -- Server versi
-- 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 */;
我的javafx代码:
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);
}
}
});
}
}
导入java.sql.Connection;
导入java.sql.DriverManager;
导入java.sql.ResultSet;
导入java.sql.SQLException;
导入java.util.Map;
导入javafx.application.application;
导入javafx.beans.property.SimpleStringProperty;
导入javafx.beans.value.ChangeListener;
导入javafx.beans.value.observeValue;
导入javafx.collections.FXCollections;
导入javafx.collections.ObservableList;
导入javafx.event.ActionEvent;
导入javafx.event.EventHandler;
导入javafx.scene.scene;
导入javafx.scene.control.Button;
导入javafx.scene.control.TableCell;
导入javafx.scene.control.TableColumn;
导入javafx.scene.control.TableColumn.CellDataFeatures;
导入javafx.scene.control.TablePosition;
导入javafx.scene.control.TableView;
导入javafx.scene.control.TableView.TableViewSelectionModel;
导入javafx.scene.control.cell.ChoiceBoxTableCell;
导入javafx.scene.control.cell.TextFieldTableCell;
导入javafx.scene.layout.BorderPane;
导入javafx.stage.stage;
导入javafx.util.Callback;
导入javafx.util.StringConverter;
类DBConnector{
专用静态连接连接器;
私有静态字符串url=“jdbc:mysql://localhost/test";
私有静态字符串user=“root”;
私有静态字符串pass=“root”;
公共静态连接connect()引发SQLException{
试一试{
Class.forName(“com.mysql.jdbc.Driver”).newInstance();
}捕获(ClassNotFoundException cnfe){
System.err.println(“错误:+cnfe.getMessage());
}捕获(实例化异常ie){
System.err.println(“错误:+ie.getMessage());
}捕获(IllegalacessException iae){
System.err.println(“错误:+iae.getMessage());
}
conn=DriverManager.getConnection(url、用户、通行证);
返回连接;
}
公共静态连接getConnection()引发SQLException,ClassNotFoundException{
如果(conn!=null&&!conn.isClosed())
返回连接;
connect();
返回连接;
}
}
公共类可动态扩展应用程序{
对象新值;
//表视图和数据
私有可观测列表数据;
私有TableView TableView;
//主要执行人
公共静态void main(字符串[]args){
发射(args);
}
//连接数据库
public void buildData(){
tableview.setEditable(true);
回拨
cellFactoryForMap=新回调(){
@凌驾
公共TableCell调用(TableP列){
返回新的TextFieldTableCell(新的StringConverter(){
@凌驾
公共字符串toString(对象t){
返回t.toString();
}
@凌驾
公共对象fromString(字符串){
返回字符串;
}
});
}
};
连接c;
data=FXCollections.observearraylist();
试一试{
c=DBConnector.connect();
//用于选择所有客户的SQL
String SQL=“选择*来自客户”;
//结果集
ResultSet rs=c.createStatement().executeQuery(SQL);
/**********************************
*动态添加的表列*
**********************************/
对于(int i=0;i您能更具体一点吗?您在哪一行遇到问题?表视图包含3列,其中一列是ObservalElist当我单击任何一行时,它会给我所有2行的数据,但没有给我ObservalElist单元格的数据,所以请帮助meSorry,我不明白您的意思。