我已将JTable设置为在同一列中显示String和Boolean值。我有以下代码来设置两种对象类型的渲染器。
table.setDefaultRenderer(Boolean.class, new BooleanHandler()); table.setDefaultRenderer(String.class, new StringHandler()); table.setDefaultRenderer( Object.class, new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { System.out.println("Inside overridden function"); return super.getTableCellRendererComponent(table, value, isSelected, hasFocus,row, column); } } );
我面临的问题是,总是调用Object的渲染器,而不是布尔值或字符串。我尝试删除对象的渲染器,仍然没有运气。
我已将JTable设置为在同一列中显示String和Boolean值
然后,您不能只使用普通的渲染逻辑。
通常,根据getColumnClass(...)方法返回的值选择渲染器。但是,这是基于列的,而不是基于单元格的,因此您将不知道要返回哪个渲染器。
getColumnClass(...)
相反,您需要重写getCellRenderer(...)和getCellEditor(...)方法以根据单元格中的数据返回渲染器/编辑器。
getCellRenderer(...)
getCellEditor(...)
下面是这种方法的示例:
import java.awt.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; public class TablePropertyEditor extends JFrame { public TablePropertyEditor() { String[] columnNames = {"Type", "Value"}; Object[][] data = { {"String", "I'm a string"}, {"Date", new Date()}, {"Integer", new Integer(123)}, {"Double", new Double(123.45)}, {"Boolean", Boolean.TRUE} }; JTable table = new JTable(data, columnNames) { private Class editingClass; public TableCellRenderer getCellRenderer(int row, int column) { editingClass = null; int modelColumn = convertColumnIndexToModel(column); if (modelColumn == 1) { Class rowClass = getModel().getValueAt(row, modelColumn).getClass(); return getDefaultRenderer( rowClass ); } else return super.getCellRenderer(row, column); } public TableCellEditor getCellEditor(int row, int column) { editingClass = null; int modelColumn = convertColumnIndexToModel(column); if (modelColumn == 1) { editingClass = getModel().getValueAt(row, modelColumn).getClass(); return getDefaultEditor( editingClass ); } else return super.getCellEditor(row, column); } // This method is also invoked by the editor when the value in the editor // component is saved in the TableModel. The class was saved when the // editor was invoked so the proper class can be created. public Class getColumnClass(int column) { return editingClass != null ? editingClass : super.getColumnClass(column); } }; table.setPreferredScrollableViewportSize(table.getPreferredSize()); JScrollPane scrollPane = new JScrollPane( table ); getContentPane().add( scrollPane ); } public static void main(String[] args) { TablePropertyEditor frame = new TablePropertyEditor(); frame.setDefaultCloseOperation( EXIT_ON_CLOSE ); frame.pack(); frame.setLocationRelativeTo( null ); frame.setVisible(true); } }
上面的代码仅使用默认的String和Boolean渲染器和编辑器。
另一种方法是创建自定义渲染器和编辑器,使每个渲染器和编辑器都知道两种可能的数据类型并返回适当的渲染器/编辑器。