【问题标题】:Stop ListView selected item from changing until button pressed停止 ListView 所选项目的更改,直到按下按钮
【发布时间】:2017-10-12 05:03:48
【问题描述】:

所以我在尝试创建的应用程序中遇到问题。我创建了一个示例应用程序来演示该问题。在应用程序中,如果未在TextField 上按下回车,我试图阻止TableView 中的选定项目更改。在我的实现中,我收到了 StackOverFlow 错误。我明白为什么我会收到错误。我基本上是在创建一个无限循环,但我想不出另一种方法来解决这个问题。

如果你去掉这行代码:

if(!validateTextFields())
{
    tvPerson.getSelectionModel().select(oldPerson);
    return;
}

如果您选择表格行,然后编辑 TextField 中的文本并在 TextField 上按 Enter,则该应用程序的工作方式与设计相同。但是,如果您选择一个表格行,编辑TextField 并且不要按回车键,用户可以选择一个新的表格行,而无需更新他/她试图编辑的表格行。所以我的问题是,如果他/她没有按回车确认TextField 编辑,我如何阻止用户更改selectedItem

控制器

import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;

/**
 *
 * @author Sedrick
 */
public class FXMLDocumentController implements Initializable {

    @FXML TextField tfFirstName, tfLastName;
    @FXML TableView<Person> tvPerson;
    @FXML TableColumn<Person, String> tcFirstName, tcLastName;

    final String firstNames = "Darryl  \n" +
                                "Enriqueta  \n" +
                                "Katherine  \n" +
                                "Harley  \n" +
                                "Arlean  \n" +
                                "Jacquelynn  \n" +
                                "Yuko  \n" +
                                "Dion  \n" +
                                "Vivan  \n" +
                                "Carly  \n" +
                                "Eldon  \n" +
                                "Joe  \n" +
                                "Klara  \n" +
                                "Shona  \n" +
                                "Delores  \n" +
                                "Sabra  \n" +
                                "Vi  \n" +
                                "Gearldine  \n" +
                                "Laine  \n" +
                                "Lila  ";

   final String lastNames = "Ollie  \n" +
                                "Donnette  \n" +
                                "Audra  \n" +
                                "Angelica  \n" +
                                "Janna  \n" +
                                "Lekisha  \n" +
                                "Michael  \n" +
                                "Tomi  \n" +
                                "Cheryl  \n" +
                                "Roni  \n" +
                                "Aurelio  \n" +
                                "Mayola  \n" +
                                "Kelsie  \n" +
                                "Britteny  \n" +
                                "Dannielle  \n" +
                                "Kym  \n" +
                                "Scotty  \n" +
                                "Deloris  \n" +
                                "Lavenia  \n" +
                                "Sun  \n";

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        tcFirstName.setCellValueFactory(new PropertyValueFactory("firstName"));
        tcLastName.setCellValueFactory(new PropertyValueFactory("lastName"));

        tvPerson.setItems(FXCollections.observableArrayList(getPersons()));
        tvPerson.getSelectionModel().selectedItemProperty().addListener((obs, oldPerson, newPerson)->{
            if(!validateTextFields())
            {
                tvPerson.getSelectionModel().select(oldPerson);
                return;
            }

            if(newPerson != null)
            {
                tfFirstName.setText(newPerson.getFirstName());
                tfLastName.setText(newPerson.getLastName());
            }
        });

        tfFirstName.setOnKeyReleased(keyEvent ->{
            Person tempPerson = tvPerson.getSelectionModel().getSelectedItem();
            if(!tfFirstName.getText().trim().equals(tempPerson.getFirstName().trim()))
            {
                tfFirstName.setStyle("-fx-control-inner-background: red;");
            }
        });

        tfFirstName.setOnAction(actionEvent ->{
            Person tempPerson = tvPerson.getSelectionModel().getSelectedItem();
            tempPerson.setFirstName(tfFirstName.getText().trim());

            tfFirstName.setStyle(null);
        });       

        tfLastName.setOnKeyReleased(keyEvent ->{
            Person tempPerson = tvPerson.getSelectionModel().getSelectedItem();
            if(tfLastName.getText().trim().equals(tempPerson.getLastName().trim()))
            {
                tfLastName.setStyle("-fx-control-inner-background: red;");
            }
        });

        tfLastName.setOnAction(actionEvent ->{
            Person tempPerson = tvPerson.getSelectionModel().getSelectedItem();
            tempPerson.setLastName(tfLastName.getText().trim());

            tfLastName.setStyle(null);
        });

    }    

    private boolean validateTextFields()
    {
        if(!tfFirstName.getStyle().isEmpty()){return false;}
        if(!tfLastName.getStyle().isEmpty()){return false;}

        return true;
    }

    List<Person> getPersons()
    {
        List<Person> tempPerson = new ArrayList();

        List<String> tempFirstName = Arrays.asList(firstNames.split("\n"));
        List<String> tempLastName = Arrays.asList(lastNames.split("\n"));

        for(int i = 0; i < tempFirstName.size(); i++)
        {
            tempPerson.add(new Person(tempFirstName.get(i).trim(), tempLastName.get(i).trim()));
        }

        return tempPerson;
    }

}

FXML

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

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>

<AnchorPane id="AnchorPane" prefHeight="575.0" prefWidth="836.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication17.FXMLDocumentController">
   <children>
      <VBox layoutX="7.0" prefHeight="200.0" prefWidth="100.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
         <children>
            <VBox prefHeight="200.0" prefWidth="100.0" spacing="5.0" VBox.vgrow="ALWAYS">
               <children>
                  <HBox spacing="5.0">
                     <children>
                        <Label prefHeight="31.0" prefWidth="72.0" text="First Name" />
                        <TextField fx:id="tfFirstName" />
                     </children>
                  </HBox>
                  <HBox spacing="5.0">
                     <children>
                        <Label prefHeight="31.0" prefWidth="72.0" text="Last Name" />
                        <TextField fx:id="tfLastName" />
                     </children>
                  </HBox>
               </children>
               <padding>
                  <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
               </padding>
            </VBox>
            <TableView fx:id="tvPerson" prefHeight="200.0" prefWidth="200.0">
              <columns>
                <TableColumn fx:id="tcFirstName" prefWidth="108.0" text="First Name" />
                <TableColumn fx:id="tcLastName" prefWidth="110.0" text="Last Name" />
              </columns>
               <VBox.margin>
                  <Insets />
               </VBox.margin>
               <padding>
                  <Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
               </padding>
            </TableView>
         </children>
      </VBox>
   </children>
</AnchorPane>

人物类

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

/**
 *
 * @author Sedrick
 */
public class Person {
    StringProperty firstName = new SimpleStringProperty();
    StringProperty lastName = new SimpleStringProperty();

    public Person(String firstName, String lastName)
    {
        this.firstName.set(firstName);
        this.lastName.set(lastName);
    }

    public StringProperty firstNameProperty()
    {
        return firstName;
    }

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

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

    public StringProperty lastNameProperty()
    {
        return lastName;
    }

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

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

}

例外

Exception in thread "JavaFX Application Thread" java.lang.StackOverflowError
    at javafx.collections.ListChangeBuilder.findSubChange(ListChangeBuilder.java:62)
    at javafx.collections.ListChangeBuilder.insertAdd(ListChangeBuilder.java:127)
    at javafx.collections.ListChangeBuilder.nextAdd(ListChangeBuilder.java:254)
    at javafx.collections.ObservableListBase.nextAdd(ObservableListBase.java:179)
    at javafx.collections.transformation.SortedList.setAllToMapping(SortedList.java:354)
    at javafx.collections.transformation.SortedList.addRemove(SortedList.java:397)
    at javafx.collections.transformation.SortedList.sourceChanged(SortedList.java:108)
    at javafx.collections.transformation.TransformationList.lambda$getListener$23(TransformationList.java:106)
    at javafx.collections.WeakListChangeListener.onChanged(WeakListChangeListener.java:88)
    at com.sun.javafx.collections.ListListenerHelper$SingleChange.fireValueChangedEvent(ListListenerHelper.java:164)
    at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
    at javafx.collections.ObservableListBase.fireChange(ObservableListBase.java:233)
    at javafx.collections.ListChangeBuilder.commit(ListChangeBuilder.java:482)
    at javafx.collections.ListChangeBuilder.endChange(ListChangeBuilder.java:541)
    at javafx.collections.ObservableListBase.endChange(ObservableListBase.java:205)
    at javafx.collections.ModifiableObservableListBase.add(ModifiableObservableListBase.java:155)
    at java.util.AbstractList.add(AbstractList.java:108)
    at com.sun.javafx.scene.control.SelectedCellsMap.add(SelectedCellsMap.java:118)
    at javafx.scene.control.TableView$TableViewArrayListSelectionModel.select(TableView.java:2456)
    at javafx.scene.control.TableView$TableViewArrayListSelectionModel.select(TableView.java:2427)
    at javafx.scene.control.TableView$TableViewArrayListSelectionModel.select(TableView.java:2485)
    at javafxapplication17.FXMLDocumentController.lambda$initialize$0(FXMLDocumentController.java:83)
    at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:182)
    at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
    at javafx.beans.property.ReadOnlyObjectPropertyBase.fireValueChangedEvent(ReadOnlyObjectPropertyBase.java:74)
    at javafx.beans.property.ReadOnlyObjectWrapper.fireValueChangedEvent(ReadOnlyObjectWrapper.java:102)
    at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112)
    at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:146)
    at javafx.scene.control.SelectionModel.setSelectedItem(SelectionModel.java:102)
    at javafx.scene.control.MultipleSelectionModelBase.lambda$new$34(MultipleSelectionModelBase.java:67)
    at com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:137)
    at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
    at javafx.beans.property.ReadOnlyIntegerPropertyBase.fireValueChangedEvent(ReadOnlyIntegerPropertyBase.java:72)
    at javafx.beans.property.ReadOnlyIntegerWrapper.fireValueChangedEvent(ReadOnlyIntegerWrapper.java:102)
    at javafx.beans.property.IntegerPropertyBase.markInvalid(IntegerPropertyBase.java:113)
    at javafx.beans.property.IntegerPropertyBase.set(IntegerPropertyBase.java:147)
    at javafx.scene.control.SelectionModel.setSelectedIndex(SelectionModel.java:68)
    at javafx.scene.control.TableView$TableViewArrayListSelectionModel.updateSelectedIndex(TableView.java:2945)
    at javafx.scene.control.TableView$TableViewArrayListSelectionModel.select(TableView.java:2458)
    at javafx.scene.control.TableView$TableViewArrayListSelectionModel.select(TableView.java:2427)
    at javafx.scene.control.TableView$TableViewArrayListSelectionModel.select(TableView.java:2485)
    at javafxapplication17.FXMLDocumentController.lambda$initialize$0(FXMLDocumentController.java:83)
    at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:182)
    at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
    at javafx.beans.property.ReadOnlyObjectPropertyBase.fireValueChangedEvent(ReadOnlyObjectPropertyBase.java:74)
    at javafx.beans.property.ReadOnlyObjectWrapper.fireValueChangedEvent(ReadOnlyObjectWrapper.java:102)
    at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112)
    at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:146)
    at javafx.scene.control.SelectionModel.setSelectedItem(SelectionModel.java:102)
    at javafx.scene.control.MultipleSelectionModelBase.lambda$new$34(MultipleSelectionModelBase.java:67)
    at com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:137)
    at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)

例外真的很长,所以我发布了一个简短的版本。

【问题讨论】:

  • 在这种情况下模式对话框可以工作吗?
  • 昨晚睡了这个之后,我想出了在对任何TextFields 进行更改后禁用TableView,并在提交所有更改后启用TableView
  • 这似乎是一种有效的方法;您可以让问题悬而未决,以获得更好的答案。
  • 实际上,我同意@trashgod - 只要核心 fx 的行为和设计与它一样糟糕,任何满足要求的解决方法都足够好(你必须以某种方式告诉用户那/为什么他们不允许更改选择,无论如何,所以禁用听起来不错)。我的回答有点像我们会用a-better-fx 做什么。顺便说一句,对于 ListView(与 TableView 相比)来说,正确处理它的机会更好,因为在那里你可以完全绕过 MultipleSelectionModelBase 并正确实现它 - 虽然需要做很多工作

标签: javafx


【解决方案1】:

基本上,“正确”的方法是自定义 selectionModel ,它具有要禁用的属性并且在该状态下不执行任何操作。不幸的是,selectionModel 不是为被自定义类扩展/替换而设计的。此外,表格控件中选择的共同祖先是 MultipleSelectionModelBase ,它既完全隐藏又非常错误。因此,使自定义模型正常运行的机会......不是很好。

尽管如此,有可能(并且投入足够的精力和资源甚至可能可靠地工作;):实现一个自定义 TableViewSelectionModel,它委托给默认实现 TableViewBitSelectionModel(它从 TableView 中获取的那个),使其自身与并将其安装到桌子上。

类似:

public static class VetoableSelection<T> extends TableViewSelectionModel<T> {

    private boolean disabled;
    private TableViewSelectionModel<T> delegate;

    public VetoableSelection(TableView<T> table) {
        super(table);
        delegate = table.getSelectionModel();
        table.setSelectionModel(this);
        new VetoableFocusModel<>(table);
        delegate.selectedIndexProperty().addListener(c -> indexInvalidated());
    }

    /**
     * keep selectedIndex in sync  
     */
    private void indexInvalidated() {
        setSelectedIndex(delegate.getSelectedIndex());
    }

    /**
     * Does nothing if disabled.
     */
    public void setDisabled(boolean disabled) {
        this.disabled = disabled;
    }

    public boolean isDisabled() {
        return disabled;
    }

    /**
     * Override all state changing methods to delegate
     * if not disabled, do nothing if disabled.
     * Here: row selection. 
     */
    @Override
    public void clearAndSelect(int row) {
        if (isDisabled()) return;
       delegate.clearAndSelect(row);
    }

    @Override
    public void select(int row) {
        if (isDisabled()) return;
        delegate.select(row);
    }

    /**
     * Here: methods with columns
     */
    @Override
    public void clearAndSelect(int row, TableColumn<T, ?> column) {
        if (isDisabled()) return;
        delegate.clearAndSelect(row, column);
    }
    @Override
    public void select(int row, TableColumn<T, ?> column) {
        if (isDisabled()) return;
        delegate.select(row, column);
    }

    ... 

对您的示例的粗略检查似乎正在起作用,有点:如果未提交修改的文本字段,它不允许更改选择。在不显示处于选定状态的单元格以及动态添加/删除人员时存在问题……可能还有一大堆其他上下文。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    相关资源
    最近更新 更多