JavaFx Tableview如何将侦听器添加到复选框列

莱昂纳多·乔苏·科西嘉

我刚刚开始使用JavaFX。我创建了一个包含3列(名称,姓氏和选择内容)的TableView。最后是复选框列。这是我的代码:

PersonTableController.java:

package ch.makery.sortfilter;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;


/**
 * View-Controller for the person table.
 * 
 * @author Marco Jakob
 */
public class PersonTableController {

    @FXML
    private TextField filterField;
    @FXML
    private TableView<Person> personTable;
    @FXML
    private TableColumn<Person, String> firstNameColumn;
    @FXML
    private TableColumn<Person, String> lastNameColumn;
    @FXML
    private TableColumn<Person, String> selectColumn; 

    private ObservableList<Person> masterData = FXCollections.observableArrayList();

    /**
     * Just add some sample data in the constructor.
     */
    public PersonTableController() {
        masterData.add(new Person("Hans", "Muster"));
        masterData.add(new Person("Ruth", "Mueller"));
        masterData.add(new Person("Heinz", "Kurz"));
        masterData.add(new Person("Cornelia", "Meier"));
        masterData.add(new Person("Werner", "Meyer"));
        masterData.add(new Person("Lydia", "Kunz"));
        masterData.add(new Person("Anna", "Best"));
        masterData.add(new Person("Stefan", "Meier"));
        masterData.add(new Person("Martin", "Mueller"));
    }

    /**
     * Initializes the controller class. This method is automatically called
     * after the fxml file has been loaded.
     * 
     * Initializes the table columns and sets up sorting and filtering.
     */
    @FXML
    private void initialize() {
        // 0. Initialize the columns.
        firstNameColumn.setCellValueFactory(cellData -> cellData.getValue().firstNameProperty());
        lastNameColumn.setCellValueFactory(cellData -> cellData.getValue().lastNameProperty());
        selectColumn.setCellValueFactory(     
                 new PropertyValueFactory<Person,String>("select")
        );  

        // 1. Wrap the ObservableList in a FilteredList (initially display all data).
        FilteredList<Person> filteredData = new FilteredList<>(masterData, p -> true);

        // 2. Set the filter Predicate whenever the filter changes.
        filterField.textProperty().addListener((observable, oldValue, newValue) -> {
            filteredData.setPredicate(person -> {
                // If filter text is empty, display all persons.
                if (newValue == null || newValue.isEmpty()) {
                    return true;
                }

                // Compare first name and last name of every person with filter text.
                String lowerCaseFilter = newValue.toLowerCase();

                if (person.getFirstName().toLowerCase().indexOf(lowerCaseFilter) != -1) {
                    return true; // Filter matches first name.
                } else if (person.getLastName().toLowerCase().indexOf(lowerCaseFilter) != -1) {
                    return true; // Filter matches last name.
                }
                return false; // Does not match.
            });
        });

        // 3. Wrap the FilteredList in a SortedList. 
        SortedList<Person> sortedData = new SortedList<>(filteredData);

        // 4. Bind the SortedList comparator to the TableView comparator.
        //    Otherwise, sorting the TableView would have no effect.
        sortedData.comparatorProperty().bind(personTable.comparatorProperty());

        // 5. Add sorted (and filtered) data to the table.
        personTable.setItems(sortedData);
    }
}

Person.java:

    package ch.makery.sortfilter;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.control.CheckBox;

/**
 * Simple model class for the person table.
 * 
 * @author Marco Jakob
 */
public class Person {

    private final StringProperty firstName;
    private final StringProperty lastName;
    private CheckBox selec = new CheckBox();    

    public Person(String firstName, String lastName) {
        this.firstName = new SimpleStringProperty(firstName);
        this.lastName = new SimpleStringProperty(lastName);     
    }

    public String getFirstName() {
        return firstName.get();
    }

    public void setFirstName(String firstName) {
        this.firstName.set(firstName);
    }

    public StringProperty firstNameProperty() {
        return firstName;
    }

    public String getLastName() {
        return lastName.get();
    }

    public void setLastName(String lastName) {
        this.lastName.set(lastName);
    }

    public StringProperty lastNameProperty() {
        return lastName;
    }

    public CheckBox getSelect() {
        return select;
    }

    public void setSelect(CheckBox select) {
        this.select = select;
    }
}

PersonTable.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane minWidth="315.0" prefHeight="300.0" prefWidth="315.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ch.makery.sortfilter.PersonTableController">
  <children>
    <TableView fx:id="personTable" prefHeight="-1.0" prefWidth="-1.0" tableMenuButtonVisible="false" AnchorPane.bottomAnchor="10.0" AnchorPane.leftAnchor="10.0" AnchorPane.rightAnchor="10.0" AnchorPane.topAnchor="40.0">
      <columns>
        <TableColumn fx:id="firstNameColumn" maxWidth="5000.0" minWidth="10.0" prefWidth="120.0" text="First Name" />
        <TableColumn fx:id="lastNameColumn" maxWidth="5000.0" minWidth="10.0" prefWidth="120.0" text="Last Name" />
        <TableColumn fx:id="selectColumn" maxWidth="5000.0" minWidth="10.0" prefWidth="120.0" text="Select" />
      </columns>
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
</columnResizePolicy>
    </TableView>
    <HBox id="HBox" alignment="CENTER" spacing="5.0" AnchorPane.leftAnchor="10.0" AnchorPane.rightAnchor="10.0" AnchorPane.topAnchor="10.0">
      <children>
        <Label text="Filter Table:" />
        <TextField fx:id="filterField" prefWidth="-1.0" HBox.hgrow="ALWAYS" />
      </children>
    </HBox>
  </children>
</AnchorPane>

我希望当时只能选择一个人,所以尝试添加一个事件或侦听器来完成此操作,但未成功。如果选中任何复选框,并且用户选中其中一个,则确定。但是,如果选中了一个复选框,同时又选中了另一个复选框,则必须取消选中第一个复选框,就像RadioButton一样。

有人可以帮助我吗?

最好的祝福

莱昂纳多·乔苏·科西嘉

谢谢@James_D。

最后,我可以实现“仅一”复选框的选择。我遵循的示例比您展示的要多:

用户检查复选框时javafx-checkboxtablecell-get-actionevent

然后将以下代码添加到调用事件:

checkedCol.setCellFactory(CheckBoxTableCell.forTableColumn(new Callback<Integer, 
ObservableValue<Boolean>>() {

        @Override
        public ObservableValue<Boolean> call(Integer param) {
            System.out.println("Cours "+coursData.get(param).getCours()+" changed value to " +coursData.get(param).isChecked());
            for (Integer i = 0; i < coursData.size(); i++) {
                if (i != param && coursData.get(param).isChecked()) {
                    coursData.get(i).setChecked(false);
                } // if
            } //  for
            return coursData.get(param).checkedProperty();
        }
    }));

对于cicle,我取消选中表中其余的复选框。

非常感谢您的帮助。

最好的祝福。

狮子座

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Javafx中将可扩展列添加到TableView?

JavaFX:如何将侦听器设置为TabPane标头的onClick事件

JavaFX:如何将侦听器设置为TabPane标头的onClick事件

如何将侦听器附加到JavaFX微调器?

如何在JavaFX中将CheckBox添加到TableView

如何将侦听器添加到使用CheckBoxListCell的列表视图中的复选框

JavaFX8:如何为Tableview中的行选择创建侦听器?

带有复选框的Javafx 8 Tableview选择

JavaFX TableView禁用复选框

将悬停侦听器添加到javafx表中特定列的单元格

JavaFX-如何将MeshView数组添加到组或场景

侦听器JavaFX

如何将侦听器添加到表?

将复选框添加到复选框组->侦听器

JavaFx Tableview,如何在同一工厂中添加侦听器并覆盖updateItem

JavaFX将事件侦听器附加到颜色为黑色的圆圈

如何将文本文件中的数据添加到 JavaFX 中的 ComboBox?

如何将控制器 (MVC) 添加到我用 Java 编写的 JavaFX 应用程序中?

如何将复选框绑定到 JavaFX 中的变量?

无法将侦听器添加到文本字段 javafx

在 javafx webview 中加载 iframe 时添加侦听器

将数组中的数据添加到 TableView javafx 的不同列

如何在 JavaFX 和 FXML 的 tableview 中选择所有复选框来创建复选框?

JavaFX - 无法将项目添加到 tableview

如何使用对象将数据添加到 JavaFX 中的空 tableview 中?

将选中的更改侦听器添加到动态添加的复选框 Xamarin Android

TableView 的 ItemProperty() 的侦听器不会失效(javafx)?

JavaFX 将 ObservableList<String> 添加到单列 TableView

不使用构建工具时如何将 JavaFX javadocs 添加到 vscode