How to use JLists in JTable cells?

I would just like to set the JList in a JTable column. I already have JLists and a table, but when they are placed in the table, Jlists are displayed as rows, which is normal because I use DefaultTableModel. I exceeded getColumnClass () as:

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

but it just formats the integer and float values.

I believe that setValueAt () and getValueAt () should also be overridden in order to return an array of string arrays when JList.getSelectedValues ​​() is called, but I cannot figure out how.
I also want the cells to be editable, so users can select one or more parameters from the JList. After editing the line, I use the "Save" button to save the changes to the database, so I don’t think I need ListSelectionListener, JList.getSelectedValues ​​() works fine.

I know this is a general question, but I could not find the answer here. If this is a duplicate, let me know and I will delete it.

+3
source share
1 answer

I have done it. For everyone who needs the same thing, here's what I did:

1) JScrollTableRenderer , , JList

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

JScrollTableRenderer:

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) JScrollTableEditor , , JList

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

JScrollTableEditor:

    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) JTable:

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

Source: https://habr.com/ru/post/1793545/


All Articles