javafx 2- tableview动态列

时间:2013-10-03 13:37:42

标签: javafx-2 tableview

有人可以在下面的代码中提出问题。我无法在表格中填充数据。 这段代码基本上应该添加一列(col1)并在其中添加一行数据d1。此代码能够添​​加列而不是数据。

控制器 -

import java.util.ArrayList;
import java.util.List;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;

public class FXMLTableViewController {
    @FXML private TableView tableView;

    @FXML
    private void initialize() {
        List<String> columns = new ArrayList<String>();
        columns.add("col1");
        TableColumn [] tableColumns = new TableColumn[columns.size()];     
        int columnIndex = 0;
        for(String columName : columns) {
            tableColumns[columnIndex++] = new TableColumn(columName);
        }
        tableView.getColumns().addAll(tableColumns);
        ObservableList<ObservableList> csvData = FXCollections.observableArrayList();
        ObservableList<String> row = FXCollections.observableArrayList();
        row.addAll("d1");
        csvData.add(row);
        tableView.getItems().add(csvData);

    }

    }

FXML

<?import javafx.collections.*?> 
<?import javafx.geometry.Insets?>
<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.control.cell.*?>
<?import javafx.scene.layout.*?>
<?import fxmltableview.*?>


<GridPane alignment="center" hgap="10.0" vgap="10.0" fx:controller="FXMLTableViewController"
             xmlns:fx="http://javafx.com/fxml">
     <TableView fx:id="tableView" GridPane.columnIndex="0" GridPane.rowIndex="1">
          <columns>
          </columns>    
     </TableView>
</GridPane>

主类 -

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class FXMLTableView extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("FXML TableView Example");
        Pane myPane = (Pane)FXMLLoader.load(getClass().getResource("fxml_tableview.fxml"));
        Scene myScene = new Scene(myPane);
        primaryStage.setScene(myScene);
        primaryStage.show();
    }

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

3 个答案:

答案 0 :(得分:6)

尝试以下代码,它将显示您需要的相同

List<String> columns = new ArrayList<String>();
    columns.add("col1");
    columns.add("col2");
    TableColumn [] tableColumns = new TableColumn[columns.size()];     
    int columnIndex = 0;
    for(int i=0 ; i<columns.size(); i++) {
        final int j = i;
        TableColumn col = new TableColumn(columns.get(i));
        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);
    }       
    ObservableList<String> row = FXCollections.observableArrayList();
    ObservableList<String> row1 = FXCollections.observableArrayList();
    row.addAll("d1");
    row.addAll("d11");
    row1.addAll("d2");
    row1.addAll("d22");
    tableview.getItems().add(row);
    tableview.getItems().add(row1);

答案 1 :(得分:1)

我相信它会对你有帮助

public class DBClass 
{    
 public Connection getConnection() throws ClassNotFoundException, SQLException 
 {       
       Class.forName("com.mysql.jdbc.Driver");
       return DriverManager.getConnection("jdbc:mysql://192.168.0.1:3306   /dbname","mysqluser","mysqluserpwd"); 
 }
}

在Controller Class中执行以下操作:

@FXML
void initialize() 
{
 assert tableview != null : "fx:id=\"tableview\" was not injected: check your FXML file 'UserMaster.fxml'.";
 colUserName.setCellValueFactory(
    new PropertyValueFactory<Usermaster,String>("userName"));        
colPassword.setCellValueFactory(                
    new PropertyValueFactory<Usermaster,String>("userPassword"));
colUserType.setCellValueFactory(
    new PropertyValueFactory<Usermaster,String>("userType"));        
colPhoto.setCellValueFactory(
    new PropertyValueFactory<Object,ImageView>("userPhoto"));
objDbClass = new DBClass();
try
{
    con = objDbClass.getConnection();
    buildData();
}
catch(ClassNotFoundException ce)
{
    logger.info(ce.toString());
}
catch(SQLException ce)
{
    logger.info(ce.toString());
}
}

private ObservableList<Usermaster> data;

public void buildData()
{        
data = FXCollections.observableArrayList();
try
{      
    String SQL = "Select * from usermaster Order By UserName";            
    ResultSet rs = con.createStatement().executeQuery(SQL);  
    while(rs.next())
    {
        Usermaster cm = new Usermaster();
        cm.userId.set(rs.getInt("UserId"));                       
        Image img = new Image("tailoring/UserPhoto/User"+cm.getUserId().toString()+".jpg");                

        ImageView mv = new ImageView();
        mv.setImage(img);
        mv.setFitWidth(70);
        mv.setFitHeight(80);
        cm.userPhoto.set(mv);
        cm.userName.set(rs.getString("UserName"));
        cm.userPassword.set(rs.getString("UserPassword"));
        cm.userType.set(rs.getString("UserType"));
        data.add(cm);                  
    }
    tableview.setItems(data);
}
catch(Exception e)
{
      e.printStackTrace();
      System.out.println("Error on Building Data");            
}
}

为每个想要使用TableView操作的实体(表)创建一个单独的java文件POJO

public class Usermaster 
{    

 public SimpleIntegerProperty userId = new SimpleIntegerProperty();
  public ObjectProperty userPhoto = new SimpleObjectProperty();
  public SimpleStringProperty userName = new SimpleStringProperty(); 
 public SimpleStringProperty userPassword = new SimpleStringProperty();
  public SimpleStringProperty userType = new SimpleStringProperty();
  public SimpleStringProperty encPass = new SimpleStringProperty();
 public SimpleStringProperty updt = new SimpleStringProperty();
  public SimpleStringProperty uptm = new SimpleStringProperty();

 public Integer getUserId() {
  return userId.get();
  }

  public Object getUserPhoto() {
  return userPhoto.get();
  }

 public String getUserName() {
  return userName.get();
  }

  public String getUserPassword() {
  return userPassword.get();
  }

  public String getUserType() {
    return userType.get();
  }

   public String getEncPass() {
   return encPass.get();
   }

   public String getUpdt() {
     return updt.get();
 }

public String getUptm() 
{
  return uptm.get();
}
}

我测试了这个程序,它运行得很好。

答案 2 :(得分:1)

我也在尝试在运行时添加列

你使用ArrayList做列很好。 你应该对tableColumns做同样的事情,否则它仍然是固定数量的列。

List<String> columns = new ArrayList<String>();
List<TableColumn> tableColumns = new ArrayList<TableColumn>; 

原因&#34; d1&#34;不会出现是因为 您已将数据正确链接到表格

tableView.getItems().add(csvData);

您忘记将数据字段链接到列,您应该添加

tableColumns[i].setCellValueFactory("sorry, I have no idea what to write here in your case");