来个简单明了的
fxml的tableview数据绑定和java代码方式的数据绑定很像,不同的在于要有一到映射
首先看个目录
1.界面文件Sample.fxml
1 xml version="1.0" encoding="UTF-8"?>
2
3 import java.lang.*?>
4 import java.util.*?>
5 import javafx.scene.control.*?>
6 import javafx.scene.layout.*?>
7 import javafx.scene.paint.*?>
8
9 <AnchorPane id&#61;"AnchorPane" maxHeight&#61;"-Infinity" maxWidth&#61;"-Infinity" minHeight&#61;"-Infinity" minWidth&#61;"-Infinity" prefHeight&#61;"400.0" prefWidth&#61;"600.0"
10 xmlns:fx&#61;"http://javafx.com/fxml" xmlns&#61;"http://javafx.com/javafx/2.2"
11 fx:controller&#61;"test.SampleController"
12 >
13 <children>
14 <TableView layoutX&#61;"132.0" layoutY&#61;"33.0" prefHeight&#61;"107.0" prefWidth&#61;"310.0" fx:id&#61;"tview">
15 <columns>
16 <TableColumn maxWidth&#61;"5000.0" minWidth&#61;"10.0" prefWidth&#61;"137.0" text&#61;"用户名" fx:id&#61;"colUsername"/>
17 <TableColumn maxWidth&#61;"5000.0" minWidth&#61;"10.0" prefWidth&#61;"143.0" text&#61;"密码" fx:id&#61;"colPassword"/>
18 columns>
19 TableView>
20 children>
21 AnchorPane>
2.SampleController代码
1 package test;
2
3 import java.net.URL;
4 import java.util.ResourceBundle;
5 import javafx.collections.FXCollections;
6 import javafx.collections.ObservableList;
7 import javafx.fxml.FXML;
8 import javafx.fxml.Initializable;
9 import javafx.scene.control.TableColumn;
10 import javafx.scene.control.TableView;
11 import javafx.scene.control.cell.PropertyValueFactory;
12
13
14 public class SampleController implements Initializable {
15
16 &#64;FXML private TableView tview;
17 &#64;FXML private TableColumn colUsername;
18 &#64;FXML private TableColumn colPassword;
19
20
21 public void showList(){
22 ObservableList
23 User user &#61; new User();//构建值对象
24 user.setUsername("小六");
25 user.setPassword("123");
26
27 colUsername.setCellValueFactory(new PropertyValueFactory("username"));//映射
28 colPassword.setCellValueFactory(new PropertyValueFactory("password"));
29
30 list.add(user); //list添加值对象
31 tview.setItems(list); //tableview添加list
32 }
33
34
35 &#64;Override
36 public void initialize(URL url, ResourceBundle rb) {
37 showList();
38 }
39 }
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 &#61; username;}public String getPassword() {return password;}public void setPassword(String password) {this.password &#61; 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 {&#64;Overridepublic void start(Stage stage) throws Exception {Parent root &#61; FXMLLoader.load(getClass().getResource("Sample.fxml"));Scene scene &#61; new Scene(root);stage.setScene(scene);stage.show();}public static void main(String[] args) {launch(args);}
}
然后达到效果