JavaFX中TableView使用

- TableView初始化代码以及在表格中使用进度条和复选框 -列表的初始化以及导入

package controlller;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ResourceBundle;

import bean.UserRow;
import comm.DataManagement;
import comm.User;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.ProgressBarTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;

@SuppressWarnings("rawtypes")
public class TableViewController extends TableView implements Initializable {
    @FXML
    private TableView<UserRow> qqInfoTable;
    private static ObservableList<UserRow> users;
    private static HashMap<String, UserRow> cache = new HashMap<>();

    @Override
    public void initialize(URL url, ResourceBundle source) {
        // qqInfoTable.getSelectionModel().setCellSelectionEnabled(true);
        dragHandler();
        initTable();
        ControllerManager.add("qqInfoTable", this);
    }

    @SuppressWarnings("unchecked")
    private void initTable() {
        // System.out.println(this==qqInfoTable);
        String[] col_Name = { "是否完成", "线程状态", "QQ", "红包状态", "当前G分", "登陆G分", "收益", "进度" };
        String[] col_Property = { "choice", "threadStatus", "qq", "packetStatus", "nowScore", "oldScore", "profit",
                "progress" };
        //设置复选框组件
        TableColumn col = new TableColumn(col_Name[0]);
        col.setEditable(true);
        col.setMinWidth(115);
        col.setCellValueFactory(new PropertyValueFactory<UserRow, CheckBox>(col_Property[0]));
        qqInfoTable.getColumns().add(col);
        for (int i = 1; i < col_Name.length; ++i) {
            col = new TableColumn(col_Name[i]);
            col.setMinWidth(115);
            col.setCellValueFactory(new PropertyValueFactory<>(col_Property[i]));
            if (i == 7) {
                col.setCellFactory(ProgressBarTableCell.forTableColumn());
            }

            qqInfoTable.getColumns().add(col);
        }
    }
    //在表格中实现拖放文件导入
    void dragHandler() {
        qqInfoTable.setOnDragOver((e)->{
            e.acceptTransferModes(TransferMode.MOVE);
        });
        qqInfoTable.setOnDragDropped((e)->{
            Dragboard board=e.getDragboard();
            if (!board.hasFiles()) {
                return;
            }
            String url=board.getFiles().get(0).getAbsolutePath();
            try {
                DataManagement.loadUsers(url);
            } catch (IOException e1) {
                ControllerManager.appendCmd(null, "加载文件错误");
            }
            insertIntoTable();
        });
    }
    //把数据插入表格
    void insertIntoTable() {
        users = FXCollections.observableArrayList();
        HashSet<User> list = DataManagement.getAllUsers();
        Iterator<User> it = list.iterator();
        while (it.hasNext()) {
            User user = it.next();
            users.add(new UserRow(user));
        }
        qqInfoTable.setItems(users);
    }

    TableView<UserRow> getTable() {
        return qqInfoTable;
    }
    //在表格中查找项目
    private UserRow find_(User user) {
        UserRow now = users.stream().filter(e -> user.equals(e)).reduce((res, next) -> res = next).get();
        cache.put(user.getQq(), now);
        return now;
    }
}

**

-TableView中使用的bean映射

**

public class User {

    protected final SimpleStringProperty qq=new SimpleStringProperty("no Login");
    protected final SimpleIntegerProperty oldScore=new SimpleIntegerProperty(0);
    protected final SimpleIntegerProperty nowScore=new SimpleIntegerProperty(0);
    protected final SimpleStringProperty nickName=new SimpleStringProperty("no Login");
    protected final SimpleIntegerProperty profit=new SimpleIntegerProperty(0);

    public User() {

    }
    protected User(User user) {
        this.qq.bind(user.qq);
        this.oldScore.bind(user.oldScore);
        this.nowScore.bind(user.nowScore);
        this.nickName.bind(user.nickName);
        this.profit.bind(user.profit);
    }
    public String getQq() {
        return qq.get();
    }
    public int getOldScore() {
        return oldScore.get();
    }
    public int getNowScore() {
        return nowScore.get();
    }

    public void setOldScore(int oldScore) {
        this.oldScore.set(oldScore);
    }

    public void setNowScore(int nowScore) {
        this.nowScore.set(nowScore);
    }
    @Override
    public int hashCode() {
        return qq.hashCode();
    }

    @Override
    public boolean equals(Object b) {
        return getQq().equals(((User)b).getQq());
    }

    public void computeProfit() {
        setProfit(nowScore.get()-oldScore.get());
    }

    public int getProfit() {
        return profit.get();
    }

    public void setProfit(int profit) {
        this.profit.set(profit);
    }
}
public class UserRow extends User{
    private static int count=1;
    private final SimpleStringProperty threadStatus=new SimpleStringProperty("no Login");
    private final SimpleStringProperty packetStatus=new SimpleStringProperty("no Login");
    private final SimpleStringProperty nickName=new SimpleStringProperty("no Login");
    private final SimpleDoubleProperty progress=new SimpleDoubleProperty(0);
    //private final SimpleBooleanProperty choice=new SimpleBooleanProperty(false);
    private final CheckBox choice=new CheckBox();
    private int sequence;

    {
        setSequence(count++);
    }

    public UserRow(User user){
        super(user);
        choice.selectedProperty().addListener(e->{
            boolean selected=choice.isSelected();
            if (selected) {
                DataManagement.addSelected(user);
            }else {
                DataManagement.removeSelected(user);
            }
        });;
    }


    public int getSequence() {
        return sequence;
    }

    public void setSequence(int sequence) {
        this.sequence = sequence;
    }

    public String getThreadStatus() {
        return threadStatus.get();
    }

    public SimpleStringProperty threadStatusProperty() {
        return threadStatus;
    }

    public String getPacketStatus() {
        return packetStatus.get();
    }

    public SimpleStringProperty packetStatusProperty() {
        return packetStatus;
    }

    public SimpleIntegerProperty oldScoreProperty() {
        return oldScore;
    }
    public String getQq() {
        return qq.get();
    }


    public String getNickName() {
        return nickName.get();
    }

    public double getProgress() {
        return progress.get();
    }
    public SimpleDoubleProperty progressProperty() {
        return progress;
    }
    public void setProgress(double progress) {
        this.progress.set(progress);
    }

    public void setThreadStatus(String threadStatus) {
        this.threadStatus.set(threadStatus);
    }

    public void setPacketStatus(String packetStatus) {
        this.packetStatus.set(packetStatus);
    }

    public SimpleIntegerProperty nowScoreProperty() {
        return nowScore;
    }

    public SimpleIntegerProperty profitProperty() {
        return profit;
    }
    /**
     * @return the choice
     */
    public CheckBox getChoice() {
        return choice;
    }

    public void allStatucSet(String status) {
        threadStatus.set(status);
        packetStatus.set(status);
    }

}

特别需要注意类似public SimpleIntegerProperty nowScoreProperty() ;此种类型的方法”属性名+Property”,属性绑定需要getter和此类方法

-效果截图
—–这里写图片描述

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
JavaFX TableView 组件是用于显示表格数据的控件。以下是使用 TableView 组件的基本步骤: 1. 首先,创建一个 TableView 对象,并设置表格的列数和行数。 ```java TableView tableView = new TableView(); tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); tableView.setPrefSize(400, 300); TableColumn column1 = new TableColumn("Column 1"); TableColumn column2 = new TableColumn("Column 2"); tableView.getColumns().addAll(column1, column2); ObservableList<ObservableList<String>> data = FXCollections.observableArrayList(); for (int i = 0; i < 10; i++) { ObservableList<String> row = FXCollections.observableArrayList(); row.add("Data " + i + "1"); row.add("Data " + i + "2"); data.add(row); } tableView.setItems(data); ``` 2. 接着,为每一列设置单元格值的提供者。 ```java column1.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> p) { return new SimpleStringProperty(p.getValue().get(0)); } }); column2.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> p) { return new SimpleStringProperty(p.getValue().get(1)); } }); ``` 3. 最后,将 TableView 对象添加到场景图。 ```java Scene scene = new Scene(new Group()); ((Group) scene.getRoot()).getChildren().addAll(tableView); primaryStage.setScene(scene); primaryStage.show(); ``` 以上就是在 JavaFX 使用 TableView 组件的基本步骤。您可以根据自己的需求进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木子的木木

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值