JAVAFX中高级TableColumn控件使用教程(用到scenebuilder)

1.表格实现效果

如下图所示,该表格具备选择框,序号以及升序和降序功能。这些功能的实现将在下文一一讲解。

2.CheckBox类的实现

在表格显示CheckBox需要单独创建一个类如下图所示,该类可以直接拿来使用。
package Model_Service;

import javafx.beans.InvalidationListener;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.CheckBox;

/**
 * Checkbox服务组件
 * @author wjz
 *
 */
public class Checkbox {
    /**
     * Checkbox组件
     */
    CheckBox checkbox=new CheckBox();
    
    /**
     * 
     * @return 返回 checkbox
     */
    public ObservableValue<CheckBox> getCheckBox()
    {
        return new  ObservableValue<CheckBox>() {
            /**
             * 添加监听
             */
            @Override
            public void addListener(ChangeListener<? super CheckBox> listener) {
            }
            /**
             * 移除监听
             */
            @Override
            public void removeListener(ChangeListener<? super CheckBox> listener) {

            }
            /**
             * 获取CheckBox
             */
            @Override
            public CheckBox getValue() {
                return checkbox;
            }
/**
 * 添加监听
 */
            @Override
            public void addListener(InvalidationListener listener) {

            }
/**
 * 移除监听
 */
            @Override
            public void removeListener(InvalidationListener listener) {

            }
        };
    }
    /**
     * 判读是否已经选中
     * @return
     */
    public Boolean isSelected()
    {
        return checkbox.isSelected();
    }
}
此外需要在实体类中声明Checkbox如下所示,声明加入transient表示Checkbox是这个类的属性一部分,但在gson序列化的过程中无需考虑。如果不添加在序列化的过程中会报错。
package Model;

import java.io.Serializable;
import java.time.LocalDate;
import Model_Service.Checkbox;

public class ServantCheck extends Servant implements Serializable {

    public ServantCheck(String id, String account, String password, String name, String gender, LocalDate birthday,
            String phoneNumber, String duty) {
        super(id, account, password, name, gender, birthday, phoneNumber, duty);
        // TODO Auto-generated constructor stub
    }

    public transient Checkbox checkbox = new Checkbox(); 
    
}

3.表格属性的声明

声明表格属性如下所示,泛型为对应的实体类
    @FXML
    private TableView<Servant> tableView;
声明表格中的一列属性如下所示,CheckBox列泛型为<实体类, CheckBox>,其余列包括序号列声明为<实体类, String>
    @FXML
    private TableColumn<Servant, CheckBox> tableColumn1;
    @FXML
    private TableColumn<Servant, String> tableColumn3;
    @FXML
    private TableColumn<Servant, String> tableColumn2;
    @FXML
    private TableColumn<Servant, String> tableColumn10;
    @FXML
    private TableColumn<Servant, String> tableColumn9;
    @FXML
    private TableColumn<Servant, LocalDate> tableColumn8;
    @FXML
    private TableColumn<Servant, String> tableColumn5;
    @FXML
    private TableColumn<Servant, String> tableColumn4;
    @FXML
    private TableColumn<Servant, String> tableColumn7;
    @FXML
    private TableColumn<Servant, String> tableColumn6;

4.显示序号方法

方法如下所示可以直接复用,只需更该泛型(<Servant>或者<Servant, String>)为自己命名的实体类即可
public void showServantTable(ObservableList<Servant> tarData) {
        tableColumn2.setCellFactory((col) -> {
            TableCell<Servant, String> cell = new TableCell<Servant, String>() {
                @Override
                public void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
                    this.setText(null);
                    this.setGraphic(null);

                    if (!empty) {
                        int rowIndex = this.getIndex() + 1;
                        this.setText(String.valueOf(rowIndex));
                    }
                }
            };
            return cell;
        });
    }
}

5.表格属性与实体类属性绑定

initialize方法如下所示
public void initialize(URL arg0, ResourceBundle arg1) { 
//表格与实体类的属性进行绑定
        this.tableColumn1.setCellValueFactory(cellData -> cellData.getValue().checkbox.getCheckBox());
        this.tableColumn3.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getId()));
        this.tableColumn4.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getAccount()));
        this.tableColumn5.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getPassword()));
        this.tableColumn6.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getName()));
        this.tableColumn7.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getGender()));
        this.tableColumn8.setCellValueFactory(cellData -> new SimpleObjectProperty(cellData.getValue().getBirthday()));
        this.tableColumn9
                .setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getPhoneNumber()));
        this.tableColumn10.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getDuty()));
        try {
            servantlist = ServantFile.servantJson();
            final ObservableList<ServantCheck> tarData = FXCollections.observableArrayList(servantlist);
            this.showServantTable(tarData);
            tableView.setItems(tarData);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
其中以下代码块负责表格属性与实体类属性的绑定
//以下代码负责绑定CheckBox,其中getValue()获取Servant实体类,checkbox为实体类中的属性
//getCheckBox()为Checkbox类中的方法
this.tableColumn1.setCellValueFactory(cellData -> cellData.getValue().checkbox.getCheckBox());

//以下代码负责绑定实体类中的属性, SimpleStringProperty表明绑定格式是String类型的
//getValue()获取Servant实体类,getPassword()为Servant实体类中的方法负责获取password(密码)
this.tableColumn5.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getPassword()));

//以下代码负责绑定实体类中的属性,SimpleObjectProperty表明绑定格式是Object类型的,兼容LocalDate
//getValue()获取Servant实体类,getBirthday()为Servant实体类中的方法负责获取birthday(出生日期)
this.tableColumn8.setCellValueFactory(cellData -> new SimpleObjectProperty(cellData.getValue().getBirthday()));
以下代码负责让表格显示数据
//以下代码负责根据为文件实例化list<servant>对象
servantlist = ServantFile.servantJson();

//以下代码负责将list<servant>对象表格可以读取的数据类型
final ObservableList<Servant> tarData = FXCollections.observableArrayList(servantlist);

//以下代码负责显示序号
this.showServantTable(tarData);

//以下代码负责将list<servant>属性添加至表格中,即让表格显示文件中的属性
tableView.setItems(tarData);

6.判断CheckBox被选中的方法

该方法负责判定是否将复选框选中,如果选中返回实体类对象,否则返回空
    public ServantCheck check() {
        //获取表格数据,需要更改泛型(<Servant>)
        ObservableList<Servant> list = tableView.getItems();

        //判断复选框是否选中,此部分需要根据具体实体类的名称进行修改
        for (Servant scr : list) {
            if (scr.checkbox.isSelected()) {
                return scr;
            }
            index++;
        }
        return null;
    }

7.Controller类完成代码

该类只负责显示表格使用具体结构,按钮方法省略以便减少代码行数
package Controller;

import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.List;
import java.util.ResourceBundle;
import Model.Servant;
import Model.ServantCheck;
import Model_File.ServantFile;
import Model_Service.ServantService;
import View.Main;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.application.Application;
import javafx.fxml.Initializable;
import javafx.scene.control.*;

/**
 * 用户管理控制类
 * @author wjz
 *
 */
public class AdminController extends Application implements Initializable {
    
    @FXML
    private Button button5;

    @FXML
    private TableColumn<Servant, CheckBox> tableColumn1;

    @FXML
    private Button button4;

    @FXML
    private TableColumn<Servant, String> tableColumn3;

    @FXML
    private Button button2;

    @FXML
    private TableColumn<Servant, String> tableColumn2;

    @FXML
    private Button button3;

    @FXML
    private TableView<Servant> tableView;

    @FXML
    private TableColumn<Servant, String> tableColumn10;

    @FXML
    private TextField textField1;

    @FXML
    private TableColumn<Servant, String> tableColumn9;

    @FXML
    private TableColumn<Servant, LocalDate> tableColumn8;

    @FXML
    private Button quit;

    @FXML
    private Button search1;

    @FXML
    private TableColumn<Servant, String> tableColumn5;

    @FXML
    private TableColumn<Servant, String> tableColumn4;

    @FXML
    private Button button1;

    @FXML
    private TableColumn<Servant, String> tableColumn7;

    @FXML
    private TableColumn<Servant, String> tableColumn6;

   
    private List<Servant> servantlist;

    private List<ServantCheck> listline;

    private TextField tx1, tx2, tx3, tx4, tx7;

    private Button newButton1, newButton2, newButton3;

    private RadioButton rb1;

    private RadioButton rb2;

    private DatePicker dp;

    private ChoiceBox<String> cB;

    private ToggleGroup tG;

    private Stage newStage;
    private String s = "男";
    private int index;

    private Stage nnewStage;

    private TextField ntx1;

    private TextField ntx3;

    private TextField ntx2;

    private TextField ntx4;

    private RadioButton nrb1;

    private RadioButton nrb2;

    private TextField ntx7;

    private DatePicker ndp;

    private ChoiceBox<String> ncB;

    private ToggleGroup ntG;

    private Button nnewButton1;

    private Button nnewButton2;

    private Button nnewButton3;

    private String ns;


    public ServantCheck check() {
        ObservableList<Servant> list = tableView.getItems();
        for (Servant scr : list) {
            if (scr.checkbox.isSelected()) {
                return scr;
            }
            index++;
        }
        return null;
    }

/**
 * 提前画好函数表格
 */
    public void initialize(URL arg0, ResourceBundle arg1) { 
        this.tableColumn1.setCellValueFactory(cellData -> cellData.getValue().checkbox.getCheckBox());
        this.tableColumn3.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getId()));
        this.tableColumn4.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getAccount()));
        this.tableColumn5.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getPassword()));
        this.tableColumn6.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getName()));
        this.tableColumn7.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getGender()));
        this.tableColumn8.setCellValueFactory(cellData -> new SimpleObjectProperty(cellData.getValue().getBirthday()));
        this.tableColumn9
                .setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getPhoneNumber()));
        this.tableColumn10.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getDuty()));
        try {
            servantlist = ServantFile.servantJson();
            final ObservableList<Servant> tarData = FXCollections.observableArrayList(servantlist);
            this.showServantTable(tarData);
            tableView.setItems(tarData);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 显示序号
     * @param tarData
     */
    public void showServantTable(ObservableList<Servant> tarData) {
        tableColumn2.setCellFactory((col) -> {
            TableCell<Servant, String> cell = new TableCell<Servant, String>() {
                @Override
                public void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
                    this.setText(null);
                    this.setGraphic(null);

                    if (!empty) {
                        int rowIndex = this.getIndex() + 1;
                        this.setText(String.valueOf(rowIndex));
                    }
                }
            };
            return cell;
        });
    }
}
//这些按钮的具体方法为了节省代码行数故不一一显示
    public void start(Stage stage) throws IOException {
    }
    @FXML
    void quitAction(ActionEvent event) {
    }
    @FXML
    void buttonAction1(ActionEvent event) {
    }
    @FXML
    void buttonAction2(ActionEvent event) {
    }
    @FXML
    void buttonAction3(ActionEvent event) {
    }
    @FXML
    void buttonAction4(ActionEvent event) {
    }
    @FXML
    void searchAction1(ActionEvent event) {
    }
    @FXML
    void newAction(ActionEvent event) {
    }
  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值