来个简单明了的
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="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" 10 xmlns:fx="http://javafx.com/fxml" xmlns="http://javafx.com/javafx/2.2" 11 fx:controller="test.SampleController" 12 > 13 <children> 14 <TableView layoutX="132.0" layoutY="33.0" prefHeight="107.0" prefWidth="310.0" fx:id="tview"> 15 <columns> 16 <TableColumn maxWidth="5000.0" minWidth="10.0" prefWidth="137.0" text="用户名" fx:id="colUsername"/> 17 <TableColumn maxWidth="5000.0" minWidth="10.0" prefWidth="143.0" text="密码" fx:id="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 @FXML private TableView tview; 17 @FXML private TableColumn colUsername; 18 @FXML private TableColumn colPassword; 19 20 21 public void showList(){ 22 ObservableList<User> list = FXCollections.observableArrayList(); 23 User user = 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 @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 = 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); } }
然后达到效果