来个简单明了的
fxml的tableview数据绑定和java代码方式的数据绑定很像,不同的在于要有一到映射
首先看个目录
1.界面文件Sample.fxml
<?xml version="1.0" encoding="UTF-8"?> <?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?> <AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0"
xmlns:fx="http://javafx.com/fxml" xmlns="http://javafx.com/javafx/2.2"
fx:controller="test.SampleController"
>
<children>
<TableView layoutX="132.0" layoutY="33.0" prefHeight="107.0" prefWidth="310.0" fx:id="tview">
<columns>
<TableColumn maxWidth="5000.0" minWidth="10.0" prefWidth="137.0" text="用户名" fx:id="colUsername"/>
<TableColumn maxWidth="5000.0" minWidth="10.0" prefWidth="143.0" text="密码" fx:id="colPassword"/>
</columns>
</TableView>
</children>
</AnchorPane>
2.SampleController代码
package test; import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory; public class SampleController implements Initializable { @FXML private TableView tview;
@FXML private TableColumn colUsername;
@FXML private TableColumn colPassword; public void showList(){
ObservableList<User> list = FXCollections.observableArrayList();
User user = new User();//构建值对象
user.setUsername("小六");
user.setPassword("123"); colUsername.setCellValueFactory(new PropertyValueFactory("username"));//映射
colPassword.setCellValueFactory(new PropertyValueFactory("password")); list.add(user); //list添加值对象
tview.setItems(list); //tableview添加list
} @Override
public void initialize(URL url, ResourceBundle rb) {
showList();
}
}
3.User.java代码
package test;
public class User {
private String username;
private String password; public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
4.Test.java
package test; import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage; public class Test extends Application { @Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
} public static void main(String[] args) {
launch(args);
}
}
然后达到效果