0

私はまだJavaFXの初心者です。クエリを実行したテーブルのコンテンツを印刷できます。問題は、コンテンツをテーブルビュー内に配置することです。これは私が行ったコードです。

public class TableViewController  implements Initializable{


@FXML
private TableView<studentInfo> tblViewer = new TableView();
@FXML
private TableColumn colID = new TableColumn();
@FXML
private TableColumn colName = new TableColumn();
@FXML
private TableColumn colAddress = new TableColumn();
@FXML
private TableColumn colAge = new TableColumn();
@FXML
private TableColumn colContact = new TableColumn();
@FXML
private Button cmdTest;

@Override
public void initialize(URL url, ResourceBundle rb) {
    // TODO
    System.out.println("READ");
    System.out.println(this.getClass().getSimpleName() + ".initialize"); 
    cmdTest.setOnAction(new EventHandler<ActionEvent>() {            
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Button Pressed");

                colID.setCellValueFactory(new PropertyValueFactory<studentInfo, Integer>("id"));
                colName.setCellValueFactory(new PropertyValueFactory<studentInfo, String>("name"));
                colAddress.setCellValueFactory(new PropertyValueFactory<studentInfo, String>("address"));
                colAge.setCellValueFactory(new PropertyValueFactory<studentInfo, Integer>("age"));
                colContact.setCellValueFactory(new PropertyValueFactory<studentInfo, String>("contact_num"));
                tblViewer.getItems().setAll(getAllstudentInfo());
            }
        } );       
}

public class studentInfo{

    private final SimpleIntegerProperty idCol;
    private final SimpleStringProperty nameCol;
    private final SimpleStringProperty addressCol;
    private final SimpleIntegerProperty ageCol;
    private final SimpleStringProperty contact_numCol;

    public studentInfo(Integer id, String name, String address, Integer age, String contact_num){
        this.idCol = new SimpleIntegerProperty(id);
        this.nameCol = new SimpleStringProperty(name);
        this.addressCol = new SimpleStringProperty(address);
        this.ageCol = new SimpleIntegerProperty(age);
        this.contact_numCol = new SimpleStringProperty(contact_num);
      }  
      public Integer getidCol(){
          return idCol.get();
      }
      public void setidCol(Integer id){
          idCol.set(id);      
      }
      public String getnameCol(){
          return nameCol.get();
      }
      public void setnameCol(String name){
          nameCol.set(name);
      }
      public String getaddressCol(){
          return addressCol.get();
      }
      public void setaddressCol(String address){
          addressCol.set(address);
      }
      public Integer getageCol(){
          return ageCol.get();
      }
      public void setageCol(Integer age){
          ageCol.set(age);
      }
      public String getcontact_numCol(){
          return contact_numCol.get();
      }
      public void setcontact_numCol(String contact_num){
          contact_numCol.set(contact_num);
      }        
}

//public static ObservableList<COA> getAllCOA(){
public List<studentInfo> getAllstudentInfo(){
    Connection conn;
    List ll = new LinkedList();
    Statement st;
    ResultSet rs;
    String url = "jdbc:mysql://localhost/java_test";
    String user = "root";
    String pass = "";
    String driver = "com.mysql.jdbc.Driver";

    try{
        Class.forName(driver);
        conn = DriverManager.getConnection(url, user, pass);
        st = conn.createStatement();
        String recordQuery = ("Select * from student");            
        rs = st.executeQuery(recordQuery);
        while(rs.next()){                
            Integer id = rs.getInt("id");
            String name = rs.getString("name");
            String address = rs.getString("address");
            Integer age = rs.getInt("age");
            String contact_num = rs.getString("contact_num");

            ll.add(new studentInfo(id, name, address, age, contact_num));
            System.out.println(id +","+ name +","+ address +","+ age +","+ contact_num +" "+"added.");
        }            
    }catch(ClassNotFoundException | SQLException ex){
        Logger.getLogger(TableViewController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return ll;        
}

}

私を助けてください。

4

1 に答える 1

-1

テーブルにデータを入力するために使用する defaultTableModel クラスを作成します。そうすることの利点は、同じクラスを使用して、可能なすべての将来のテーブルにもデータを入力できるようにすることです。ここに私が過去に使用したものがあります:

public class DefTableModel {
static DefaultTableModel buildTableModel(ResultSet rs)throws SQLException {

    ResultSetMetaData metaData = rs.getMetaData();
    Vector<String> columnNames = new Vector<String>();
    int columnCount = metaData.getColumnCount();
    for (int column = 1; column <= columnCount; column++) {
        columnNames.add(metaData.getColumnName(column));
    }
    Vector<Vector<Object>> data = new Vector<Vector<Object>>();
    while (rs.next()) {
        Vector<Object> vector = new Vector<Object>();
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
            vector.add(rs.getObject(columnIndex));
        }
        data.add(vector);
    }
    DefaultTableModel tableModel = new DefaultTableModel(data, columnNames) {
        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };              
    return  tableModel;
    }
}

次に、テーブルを作成するメソッドで、必要なすべてのコンポーネントを初期化します。

public void methodNameHere(){
 PreparedStatement searchParameter=null;
 ResultSet rs=null;
 ConnectionClass connServer = new ConnectionClass();
 Connection conn=connServer.databaseConnect();
 try{
   searchParameter=conn.prepareStatement("SELECT * FROM student");
   rs = searchParameter.executeQuery(); 
    if(!rs.isBeforeFirst()){

    rs.close();
    searchParameter.close();  //dont forget to close all if nothing is found
    conn.close();
   }
  else{
     tableName.setModel(DefTableModel.buildTableModel(rs));
  }
 catch (SQLException e){
   //do something if you get an sql exception
 }
 catch (Exception e2){
  //do something incase of any other exception
 }
 finally {
     rs.close();
 searchParameter.close();  //dont forget to close all when done.
 conn.close();
 }

必要に応じて、SQL 文 "SELECT (nameOfColumn) AS (newNameOfColumn)" を変更することで、テーブル内の列の名前を設定することもできます。ここで提供したこのテーブル モデルは、データベース テーブルの列名から列名を直接取得するためです。 。 お役に立てれば。

于 2013-06-27T11:01:19.323 に答える