简体   繁体   English

如何获取JTable中显示的单元格值(不是完整的TableModel值)?

[英]How can i get the displayed cell value in a JTable (not full TableModel value)?

Normally, I get the value of a table cell in JTable using 通常,我使用以下方法在JTable获取表单元格的值:

table.getModel().getValueAt(rowIndex, columnIndex)

However, now I have a given input JTable (which I don't control or create) and need to get the displayed cell value as a String . 但是,现在我有了给定的输入JTable (我无法控制或创建),并且需要获取显示的单元格值作为String If the value is a Double , it can have more digits than are displayed by the JTable . 如果值为Double ,则它的位数可以超过JTable所显示的位数。

Example: The JTable displays 0.37 (two digits) - but getValueAt returns 0.37234421 示例: JTable显示0.37(两位数字)-但是getValueAt返回0.37234421

What I'm looking for is either get the displayed value as a String , or the # of digits displayed (so I can change the double from getValueAt accordingly()... 我正在寻找的是要么以String形式获取显示的值 ,要么是显示的位数(因此我可以从getValueAt相应地更改double()。

The brute force method would be 蛮力法是

Object value = jtable.getValueAt(row, column);
Component component = jtable.getCellRenderer(row, column).getTableCellRendererComponent(jtable, value, isSelected, hasFocus, row, column);
if (component instanceof JLabel) {
    String displayedValue = ((JLabel) component).getText(); // here you are
}

Beware the CellRenderer of a JTable can be replaced by someone by calling eg jtable.setDefaultRenderer(columnClass, renderer) . 注意 ,可以通过调用例如jtable.setDefaultRenderer(columnClass, renderer)来替换JTableCellRenderer Then, depending on the implementation, the resulting Component might not be a JLabel any more. 然后,根据实现的不同,生成的Component可能不再是JLabel In the latter case a different logic is needed to retrieve the displayed value (ie cast component to different Class and retrieve it from that instance). 在后一种情况下,需要不同的逻辑来检索显示的值(即,将component为不同的Class并从该实例中检索它)。 However the DefaultTableCellRenderer implementation which is used by JTable by default returns a JLabel . 但是 ,默认情况下,由JTable使用的DefaultTableCellRenderer实现返回JLabel

BUT The value you see could be different from this as well .... if the column in the table is not wide enough in your table the text 23.4567 could be the text but the actually displayed text is 23.4... ... If you want to know the factually displayed value a different approach is needed... 但是 ,您看到的值也可能与此不同....如果表中的列在表中不够宽,则文本23.4567可能是文本,但实际显示的文本是23.4... ...如果您想知道实际显示的价值,需要使用其他方法...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM