栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

类特定的渲染器组件未调用

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

类特定的渲染器组件未调用

我已将JTable设置为在同一列中显示String和Boolean值

然后,您不能只使用普通的渲染逻辑。

通常,根据

getColumnClass(...)
方法返回的值选择渲染器。但是,这是基于列的,而不是基于单元格的,因此您将不知道要返回哪个渲染器。

相反,您需要重写

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渲染器和编辑器。

另一种方法是创建自定义渲染器和编辑器,使每个渲染器和编辑器都知道两种可能的数据类型并返回适当的渲染器/编辑器。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/446936.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号