开发者

How to use JLists in JTable cells?

I would like a simple way to put a JList in a column of a JTable. I already have the JLists and the table, but when put in the table, the Jlists are displayed as Strings, which is normal, because I use DefaultTableModel. I have overriden the getColumnClass() as:

public Class<? extends Object> getColumnClass(int c)
{
    return getValueAt(0, c).getClass();
}

but this just formats the integer and float values.

开发者_运维技巧

I suppose that setValueAt() and getValueAt() should also be overriden, in order to return am array of Strings when I call JList.getSelectedValues(), but I can't figure out how.

I also want the cells to be editable, so the users can choose one or more option from the JList. After editing a row, I use a Save button to save the changes in a database, so I don't think I need a ListSelectionListener, JList.getSelectedValues() works just fine.

I know this is a common question, but I couldn't find an answer here. If this is a duplicate, please let me know and I will delete it.


I've done it. For everyone who needs the same thing, here is what I've done:

1)I have created a JScrollTableRenderer, and set the column I needed to show the JList to use this renderer

    table.getColumnModel().getColumn(5).setCellRenderer(new JScrollTableRenderer());

The JScrollTableRenderer class content:

public class JScrollTableRenderer extends DefaultTableCellRenderer {

JScrollPane pane = new JScrollPane();

public JScrollTableRenderer()
{
    super();
}

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
      boolean hasFocus, int row, int column)
{
    pane = (JScrollPane) value;
    return pane;
}
}

2)I have created a JScrollTableEditor, and set the column I needed to show the JList to use this editor

    table.getColumnModel().getColumn(5).setCellEditor(new JScrollTableEditor());

The JScrollTableEditor class content:

    public class JScrollTableEditor extends AbstractCellEditor implements TableCellEditor {
    JScrollPane component = new JScrollPane();
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
          int rowIndex, int vColIndex)
    {
        component = ((JScrollPane) value);
        return ((JScrollPane) value);
    }

    public Object getCellEditorValue()
    {
        return component;
    }

    }

3)I added this method in the JTable model:

            public Class<? extends Object> getColumnClass(int c)
            {
                if(c == 5) return JScrollPane.class;
                else return getValueAt(0, c).getClass();
            }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜