我试图使用TableView创建一个Jruby应用程序,但我还没有能够使用数据填充表格,甚至找不到一些示例代码。这是我的fxml的相关部分:
<TableView prefHeight="400.0" prefWidth="200.0" id="table">
<columns>
<TableColumn prefWidth="75.0" text="name">
<cellValueFactory>
<PropertyValueFactory property="name" />
</cellValueFactory>
</TableColumn>
<TableColumn prefWidth="75.0" text="address">
<cellValueFactory>
<PropertyValueFactory property="address" />
</cellValueFactory>
</TableColumn>
</columns>
</TableView>
以下是相关的红宝石代码:
class Person
attr_accessor :name, :address
def initialize
@name = 'foo'
@address = 'bar'
end
end
class HelloWorldApp < JRubyFX::Application
def start(stage)
with(stage, title: "Hello World!", width: 800, height: 600) do
fxml HelloWorldController
@data = observable_array_list
@data.add Person.new
stage['#table'].set_items @data
show
end
end
end
有人可以建议我做错了什么或者指出我正在使用的示例代码吗?
答案 0 :(得分:1)
参见contrib/fxmltableview样本;我认为这正是你想要做的。您遇到的问题是PropertyValueFactory
是一个Java类,它正在尝试访问一个JRuby类的Person
。默认情况下,此功能无法显示,但您可以通过调用Person.become_java!
轻松解决此问题。但是,即使您这样做,它也不会起作用,因为PropertyValueFactory
期望格式为[javatype] get[PropertyName]()
的getter方法,而attr_accessor
只生成[rubytype] [propertyname]()
形式的getter方法。要解决此问题,请使用fxml_accessor
来生成正确的方法(但不使用@
vars,这些是原始属性实例):
class Person
include JRubyFX # gain access to fxml_accessor
# must specify type as the concrete `Property` implementation
fxml_accessor :name, SimpleStringProperty
fxml_accessor :address, SimpleStringProperty
def initialize
# note use of self to call the method Person#name= instead of creating local variable
self.name = 'foo'
self.address = 'bar'
# could also technically use @address.setValue('bar'), but that isn't as rubyish
end
end
# become_java! is needed whenever you pass JRuby objects to java classes
# that try to call methods on them, such as this case. If you used your own
# cellValueFactory, this probably would not be necessary on person, but still
# needed on your CVF
Person.become_java!