【问题标题】:Java - incorrect action at selecting a checkboxJava - 选择复选框时的错误操作
【发布时间】:2020-02-22 00:48:30
【问题描述】:

我从事 Java FX 工作。
我有一个表格视图,在其中创建了一个“选择复选框”列。目标是当用户单击复选框时,会出现一条警告消息。
为了测试它,我首先尝试显示 System.out.println 消息。
问题是:

  • 当我只选择一个复选框时,我会收到一条 System.out.println 消息,其中会写入所有复选框:
com.calculatrice.app.model.Person@34752060
com.calculatrice.app.model.Person@654bd7bc
com.calculatrice.app.model.Person@74bbebe0
com.calculatrice.app.model.Person@2e23be4f
com.calculatrice.app.model.Person@3348edcb
com.calculatrice.app.model.Person@8052a29
com.calculatrice.app.model.Person@23ca3422
com.calculatrice.app.model.Person@102837d2
com.calculatrice.app.model.Person@647ab6a9
  • 当我什么都不选择时,我有相同的 System.out.println 消息

我怎么能有一个与项目对应的消息,对应于选中的复选框?

这是我的 sn-p:

  private void selectCheckBox(ActionEvent ae) {
         // personTable is the Tableview ; Person is the class where the getter is declared
        for(Person p : personTable.getItems()){
            if (p.getSelect().isSelected()){
                System.out.println (p + " is selected");
            }
        }
}

【问题讨论】:

  • 我认为覆盖toString 方法将有助于解决这个问题。好吧,我想这不是一个真正的问题,因为这是预期的行为。
  • 好的,谢谢您的回答。可以问一下怎么做吗?
  • 请提供一个minimal reproducible example 来说明问题。
  • 我不知道你的实现是什么,但如果 Person 上的选定字段不是完整的 BooleanProperty 并且你没有使用 CheckboxTableCell,你可能应该是。您可能还存在我们看不到的代码中的其他问题。

标签: java javafx checkbox


【解决方案1】:

您可以标记复选框,然后使用 getLabel 获取它们的名称。

        if (p.getSelect().isSelected()){
            System.out.println (p.getLabel() + " is selected");
        }

或者,如果您不想要可见标签,您可以使用setNamegetName

【讨论】:

  • 感谢您的回答。问题是我仍然看到相同的行为。当我选择一个复选框时,消息会返回每个复选框的标签。
  • 我只是在猜测,但问题可能出在 Person 类的内部实现中
  • 此外,如果您使用绑定,请确保在适当的时间绑定和解除绑定。当我开始使用 javafx 时,我最终会将 100 个东西绑定到一个控件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-02
  • 2012-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多