填充TableView在JavaFX中使用在FXML文件中创建的TableView [英] Populating TableView In JavaFX with TableView created in FXML File

查看:754
本文介绍了填充TableView在JavaFX中使用在FXML文件中创建的TableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaFX的新手,也是java的。如果缺少的,我可以使用println函数从数据库打印项目,你可以找出这个代码。

  public class TableViewController implements可初始化{

@FXML
private TableView< studentInfo> tblViewer = new TableView< studentInfo>();
@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());
//tblViewer.getColumns().addAll(colID,colName,colAddress,colAge,colContact );
//System.out.println(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(){
返回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 List< studentInfo> getAllstudentInfo(){
Connection conn;
List ll = new LinkedList();
语句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()){
整数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;
}

这是FXML文件:

 <?import java.lang。*?> 
<?import java.util。*?>
<?import javafx.scene。*?>
<?import javafx.scene.control。*?>
<?import javafx.scene.layout。*?>

< AnchorPane id =AnchorPaneprefHeight =594.0prefWidth =838.0xmlns:fx =http://javafx.com/fxmlfx:controller =loadingcsvtotableview.TableViewController >
< children>
< TableView fx:id =tblViewerprefHeight =521.0prefWidth =808.0AnchorPane.bottomAnchor =14.0AnchorPane.leftAnchor =15.0AnchorPane.rightAnchor =15.0AnchorPane.topAnchor = 59.0>
< columns>
< TableColumn prefWidth =75.0text =IDfx:id =colID/>
< TableColumn prefWidth =175.0text =Namefx:id =colName/>
< TableColumn prefWidth =330.0text =Addressfx:id =colAddress/>
< TableColumn prefWidth =75.0text =Agefx:id =colAge/>
< TableColumn prefWidth =150.0text =联系电话fx:id =colContact/>
< / columns>
< / TableView>
< Button fx:id =cmdExportlayoutX =14.0mnemonicParsing =falseprefHeight =30.0prefWidth =112.0text =Export DataAnchorPane.topAnchor =21.0/>
< Button fx:id =cmdCloselayoutX =144.0mnemonicParsing =falseprefHeight =30.0prefWidth =112.0text =CloseAnchorPane.topAnchor =21.0/>
< Button id =cmdClosefx:id =cmdTestlayoutX =386.0layoutY =21.0mnemonicParsing =falseprefHeight =30.0prefWidth =112.0text = >
< / children>
< / AnchorPane>

我缺少什么?请帮助我..

解决方案

属性值工厂与您的bean中的任何getter和setters函数不匹配。因此,如果您将单元格值工厂设置为下一个:

  colID.setCellValueFactory(new PropertyValueFactory< studentInfo,Integer> )); 

属性值工厂将查找函数getId(),setId()和idProperty最后一个返回属性本身,你在你的bean中。检查 PropertyValueFactory API和表格视图教程深入了解。



也可以做agon_说,你创建一个列两次。



有几件事。您每次单击按钮时设置CellValueFactory。



函数getAllstudentInfo()会阻塞你的GUI,因为查询是阻塞的。



因此请替换您的 tblViewer.getItems()。setAll(getAllstudentInfo()); 到如下:

 服务< ObservableList< studentInfo> service = new Service< ObservableList< studentInfo>>(){
@Override
protected Task< ObservableList< studentInfo> createTask(){
return new Task< ObservableList< studentInfo>>(){
@Override
protected ObservableList< studentInfo> call()throws Exception {
return FXCollections.observableArrayList(getAllstudentInfo());
}
};
}
};
tblViewer.itemsProperty()。bind(service.valueProperty());
service.start();

查看 JavaFX 2的并发教程肯定会帮助你。



希望它有帮助。 / p>

I am a newbie in JavaFX and also in java. Guys can you please figure out this code if what is lacking because I can already print the items from the database using the println function.

public class TableViewController  implements Initializable{

@FXML
private TableView<studentInfo> tblViewer = new TableView<studentInfo>();
@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());
    //tblViewer.getColumns().addAll(colID, colName, colAddress, colAge, colContact);
    //System.out.println(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 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;
}

And this is the FXML File:

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" prefHeight="594.0" prefWidth="838.0" xmlns:fx="http://javafx.com/fxml" fx:controller="loadingcsvtotableview.TableViewController">
<children>
<TableView fx:id="tblViewer" prefHeight="521.0" prefWidth="808.0" AnchorPane.bottomAnchor="14.0" AnchorPane.leftAnchor="15.0" AnchorPane.rightAnchor="15.0" AnchorPane.topAnchor="59.0">
  <columns>
    <TableColumn prefWidth="75.0" text="ID" fx:id="colID" />
    <TableColumn prefWidth="175.0" text="Name" fx:id="colName" />
    <TableColumn prefWidth="330.0" text="Address" fx:id="colAddress" />
    <TableColumn prefWidth="75.0" text="Age" fx:id="colAge" />
    <TableColumn prefWidth="150.0" text="Contact Number" fx:id="colContact" />
  </columns>
 </TableView>
 <Button fx:id="cmdExport" layoutX="14.0" mnemonicParsing="false" prefHeight="30.0" prefWidth="112.0" text="Export Data" AnchorPane.topAnchor="21.0" />
 <Button fx:id="cmdClose" layoutX="144.0" mnemonicParsing="false" prefHeight="30.0" prefWidth="112.0" text="Close" AnchorPane.topAnchor="21.0" />
 <Button id="cmdClose" fx:id="cmdTest" layoutX="386.0" layoutY="21.0" mnemonicParsing="false" prefHeight="30.0" prefWidth="112.0" text="Test" />
 </children>
</AnchorPane>

What do Am I Lacking? Please help me guys..

解决方案

The Property Value Factory doesn't match with any getters and setters function in your bean. So if you set the cell value factory as the next:

colID.setCellValueFactory(new PropertyValueFactory<studentInfo, Integer>("id"));

The property value factory will look for the function getId(), setId() and idProperty(). The last one returns the property itself, that you have in your bean. Check the API of PropertyValueFactory and the tutorial of Table View to go deep on this.

Also do what agonist_ says, you are creating a the column twice.

There are a couple things. You are setting the CellValueFactory every time you click on the button. You need to put it in the initialize not in the button event.

And the function getAllstudentInfo() will block your GUI, because the query it's blocking. You should do this in a background thread.

So replace your tblViewer.getItems().setAll(getAllstudentInfo()); to something like:

Service<ObservableList<studentInfo>> service = new Service<ObservableList<studentInfo>>() {                 
@Override
protected Task<ObservableList<studentInfo>> createTask() {
    return new Task<ObservableList<studentInfo>>() {                            
        @Override
        protected ObservableList<studentInfo> call() throws Exception {
            return FXCollections.observableArrayList(getAllstudentInfo());
        }
    };
}
};
tblViewer.itemsProperty().bind(service.valueProperty());        
service.start();

Take a look on concurrency tutorial of JavaFX 2 sure will help you.

Hope it helps.

这篇关于填充TableView在JavaFX中使用在FXML文件中创建的TableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆