如何在setResultConverter中引用非声明的变量

时间:2015-10-21 00:53:40

标签: javafx dialog dynamic-variables

我想重新使用对话框类进行数据操作。将从数据库中检索数据。它取决于类从哪个表中检索数据,表列的大小是不固定的,所以我不能声明列变量。用户更新数据后,我想使用setResultConverter转换输入数据,但不知道如何引用变量,因为程序动态生成TextFields。请帮忙。这是代码。

public class AddDialog {
   private Dialog<DBtable> dialog = new Dialog<DBtable>();
   private ButtonType saveBtn;
   //database variables
  private Connection connect; // = null;
  private String dbTblName;
   //gridpane content variables
  private GridPane contentPane = new GridPane();
  private HashMap<String, TextField> fieldMap = 
                 new HashMap<String, TextField>();
  private ArrayList<String> dataList = new ArrayList<String>();

   public AddDialog (String title, String header, String dbTable) {
       this.dbTblName = dbTable;

       dialog.setTitle(title);
       dialog.setHeaderText(header);

       saveBtn = new ButtonType("Save", ButtonData.OK_DONE);
       dialog.getDialogPane().getButtonTypes().addAll(saveBtn, 
                                          ButtonType.CANCEL);

       dialog.getDialogPane().setContent(getLayout(dbTable));

      Optional<DBtable> result = dialog.showAndWait();

      result.ifPresent(data -> {
               System.out.println(" data="+data+" 0="+data.getID()+
        " 1="+data.getField1());
        });

 } // constructor ends

public GridPane getLayout(String dbTable) {
String  sql =   "select column_name, description ";
    sql +=  "from   syscolumn_description ";
    sql +=  "where  table_name = \'" + dbTable + "\'";
String fieldLabel, fieldCol;
ResultSet ds = null;
// retrieve meta data from database

connect  = DBConnect.getConnect(connect);
try {
   Statement labelStmnt = connect.createStatement();
   ds = labelStmnt.executeQuery(sql);

   int row = 0;
   while (ds.next()) {
    row += 2;
    //label....column=0 row=row+2;
    fieldLabel = ds.getString("DESCRIPTION");
    contentPane.add(new Text(fieldLabel), 0, row);

    //textField...column=1 row=row+2;
    contentPane.add(new TextField(), 1, row);
    fieldCol = ds.getString("COLUMN_NAME");
    fieldMap.put(fieldCol, new TextField());

   } // while result set loop ends
} catch (Exception e) {
   e.printStackTrace();
} finally {
   try {if(ds != null) ds.close();} catch (Exception e) {};
}

    // convert result
dialog.setResultConverter(dialogButton -> {
    if (dialogButton == saveBtn) {
       int i=0;
       for (Map.Entry<String, TextField> e : fieldMap.entrySet()) {
        dataList.add(e.getValue().getText());
        i++;
        System.out.println("col="+e.getKey()+
            " data="+e.getValue().getText());
       } // map loop end

       return new DBtable(dataList, i);
    }
    return null;
});

return contentPane;

} //getLayout ends
} // AddDialog ends

0 个答案:

没有答案