Reputation:
I have a scrollable JTable inside a JDialog and i wish to autoadjust the row width according to data length.
Any ideas?
Upvotes: 0
Views: 368
Reputation: 347184
This depends on what is being rendered and if you know the number if pixels...
Changing the column widths will be effected by the column auto resize policy.
If you want to set the pixel width...
int columnIndex = //... the index of the column
TableColumnModel columnModel = table.getColumnModel();
TableColumn tableColumn = columnModel.getColumn(columnIndex);
tableColumn.setWidth(pixelWidth);
If the column is rendering text and you know the number of characters that the column will display you can get the font metrics for the renderer/table...
// If you're using a cell renderer, you will need to get the cell renderer
// to get th font metrics
FontMerics fm = table.getFontMetrics(table.getFont());
int pixelWidth = fm.stringWidth("M") * characterCount;
If you're not using a text based renderer, you can use the renderer to gain some idea of the width...
TableCellRenderer renderer = table.getCellRenderer(0, columnIndex);
// You can also use table.getDefaultRenderer(Class)
Component component = renderer.getTableCellRendererComponent(table,
prototypeValue, // Some value the best represents the average value
false,
false,
0,
columnIndex);
int width = component.getPreferredWidth().width;
Upvotes: 0
Reputation: 17359
Use the combination of JTable.setRowHeight method and a cell renderer based on JTextArea
Upvotes: 2