Home > Back-end >  Make JTable cells in specific column scrollable
Make JTable cells in specific column scrollable

Time:05-12

I'm creating GUI in java using swing. I use JTable that looks like this.My table

I need to make cells of last column("Popis") to be scrollable as there will be description so String containing this description has variable lenght for each row. This is how I created my JTable.

this.tableModel = new DefaultTableModel(
                new Object[][] { },
                new String[] {"ID", "Nazov", "Naplnena kapacita / kapacita", "Popis"}
        );
this.table1.setModel(this.tableModel);

I add data to table using this.tablemodel.addRow(); Is there a way to make cells of last column of my table scrollable?

CodePudding user response:

It would be difficult and awkward to embed a scrolling component inside a JTable. A common approach to showing long cell values is to make the cell’s tooltip (hover text) display the full value:

table1.setModel(tableModel);

table1.getColumnModel().getColumn(3).setCellRenderer(
    new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table,
                                                       Object value,
                                                       boolean selected,
                                                       boolean focused,
                                                       int row,
                                                       int column) {

            Component component = super.getTableCellRendererComponent(
                table, value, selected, focused, row, column);

            if (component instanceof JComponent) {
                ((JComponent) component).setToolTipText(
                    Objects.toString(value, null));
            }

            return component;
        }
    });

(Objects is the java.util.Objects class.)

  • Related