开发者

jRuby's Float to represent in JTable's cell

开发者 https://www.devze.com 2022-12-30 10:41 出处:网络
I need to represent floats in jTable formatted. When I do tbl.model.add_row [obj, 1.3524632478].to_java, obj is represented as it\'s to_s method\'s return value, but float do not. Overriding float\'s

I need to represent floats in jTable formatted. When I do tbl.model.add_row [obj, 1.3524632478].to_java, obj is represented as it's to_s method's return value, but float do not. Overriding float's to_s method does nothing. I want floats t开发者_开发问答o be formatted like this class Float def to_s sprintf("%.2f", self) end end in all my tables.


I would surmise that it's due to the default TableCellRenderer used calling java.lang.Float.toString(some_float) rather than some_float.to_s. So in addition to what you've already done with Float's to_s, add these:

class MyCellRenderer < Java::JavaxSwingTable::DefaultTableCellRenderer::UIResource
    def setValue(value)
        setText(value.nil? ? "" : value.to_s)
    end
end
my_cell_renderer = MyCellRenderer.new

# This to set it globally
my_table.setDefaultRenderer(java.lang.Object, my_cell_renderer)

# Or this to set it for specific columns only
my_table.column_model.getColumn(0).setCellRenderer(my_cell_renderer)


Ruby classes are converted to java classes when rows being vectorized. I added to_s method to java's Float class and its OK

0

精彩评论

暂无评论...
验证码 换一张
取 消