Line Wrapping Cell Renderer - Java

时间:2011-04-14 18:18:16

标签: swing jtable

我在实现自定义单元格渲染器时遇到问题,该渲染器会在消息内容超出一行时将其换行。以下是我所拥有的:

public class MessageTable extends JTable
{

    private static MessageTable messageTable;
    private DefaultTableModel model = new DefaultTableModel();
    private String[] emptyData = {};
    private TreeMap<Integer, String> messages = null;

    public class LineWrapCellRenderer  extends JTextArea implements TableCellRenderer {

        @Override
        public Component getTableCellRendererComponent(
                        JTable table,
                        Object value,
                        boolean isSelected,
                        boolean hasFocus,
                        int row,
                        int column) {
                this.setText((String)value);
                this.setWrapStyleWord(true);                    
                this.setLineWrap(true);      

                this.setBackground(Color.YELLOW);

                int fontHeight = this.getFontMetrics(this.getFont()).getHeight();
                int textLength = this.getText().length();
                int lines = textLength / this.getColumns() +1;//+1, because we need at least 1 row.                       
                int height = fontHeight * lines;                        
                table.setRowHeight(row, height);
                return this;
        }
    }

    public MessageTable()
    {
        super();
        messageTable = this;
        this.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);      

        model.addColumn("Message Number", emptyData);
        model.addColumn("Message Content", emptyData);

        this.setModel(model);
        this.setFont(MappingView.theFont);

        this.setDefaultRenderer(String.class, new LineWrapCellRenderer());
    }

    /**
     * Set the current messages.
     * @param messages
     */
    public void setCurrentMessages(TreeMap<Integer, String> messages)
    {
        clearCurrentMessages();

        this.messages = messages;

        if (messages != null)
        {
            for (Integer key : messages.keySet())
            {
                String[] row = { key.toString(), messages.get(key).toString() };
                model.addRow(row);
            }
        }
    }

出于某种原因,从不使用LineWrapCellRenderer,并且行只包含一行文本。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您的cellrenderer未被使用,因为默认表模型为任何列返回Object.class(它不会覆盖AbstractTableModel的实现):

public Class<?> getColumnClass(int columnIndex) { 
    return Object.class;
}

因此,要么自己为模型覆盖方法,要么将渲染器指定给Object.class