Auto resize the widths of JTable's columns dynamically - java

I have a JTable with 3 columns:
- No. #
- Name
- PhoneNumber
I want to make specific width for each column as follows:
and I want the JTable able to update the widths of its columns dynamically if needed (for example, inserting large number in the column #) and keeping same style of the JTable
I solved the first issue, using this code:
myTable.getColumnModel().getColumn(columnNumber).setPreferredWidth(columnWidth);
but I didn't success to make myTable to update the widths dynamically ONLY if the current width of the column doesn't fit its contents. Can you help me solving this issue?

Here I found my answer: http://tips4java.wordpress.com/2008/11/10/table-column-adjuster/
The idea is to check some rows' content length to adjust the column width.
In the article, the author provided a full code in a downloadable java file.
JTable table = new JTable( ... );
table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
for (int column = 0; column < table.getColumnCount(); column++)
{
TableColumn tableColumn = table.getColumnModel().getColumn(column);
int preferredWidth = tableColumn.getMinWidth();
int maxWidth = tableColumn.getMaxWidth();
for (int row = 0; row < table.getRowCount(); row++)
{
TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
Component c = table.prepareRenderer(cellRenderer, row, column);
int width = c.getPreferredSize().width + table.getIntercellSpacing().width;
preferredWidth = Math.max(preferredWidth, width);
// We've exceeded the maximum width, no need to check other rows
if (preferredWidth >= maxWidth)
{
preferredWidth = maxWidth;
break;
}
}
tableColumn.setPreferredWidth( preferredWidth );
}

Use the addRow(...) method of the DefaultTableModel to add data to the table dynamically.
Update:
To adjust the width of a visible column I think you need to use:
tableColumn.setWidth(...);

I actually run into this problem too. I've found one useful link that solved my issue.
Pretty much get the specific column and set its setMinWidth and setMaxWidth to be the same(as fixed.)
private void fixWidth(final JTable table, final int columnIndex, final int width) {
TableColumn column = table.getColumnModel().getColumn(columnIndex);
column.setMinWidth(width);
column.setMaxWidth(width);
column.setPreferredWidth(width);
}
Ref: https://forums.oracle.com/thread/1353172

Related

Increasing height of jtable dynamically upon insertion of rows

I am having a problem on adjusting the height of a jtable whenever I insert rows. I have tried using setsize() and setPreferredScrollableViewportsize() for both table and scrollpane of the table. Could it be a problem in layout manager?
I also tried increasing the size of jpanel too upon inserting each row. BTW, the table lies in a panel and that panel lies in a jDialog. I am using free design in NetBeans for UI building.
Try the following... But make sure you editable option is false!
DefaultTableModel model = (DefaultTableModel)table.getModel();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
final TableColumnModel colModel = table.getColumnModel();
for(int column=0; column<table.getColumnCount();column++){
int width = 15;
for(int row=0; row<table.getRowCount();row++){
TableCellRenderer render = table.getCellRenderer(row, column);
Component component = table.prepareRenderer(render, row, column);
width = Math.max(component.getPreferredSize().width+1, width);
}
if(width>300){
width = 300;
colModel.getColumn(column).setPreferredWidth(width);
}
}

JTable Column Headers with wrapped and center aligned text

I am currently trying to wrap and align center text of a column header. The problem seems to be that while the first line of column header is aligned, the second one does not get aligned properly.
I am using DefaultTableCellRenderer to render it as such:
public void centerAlign(JTable t, int numberOfColumns){
centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
for (int i = 0; i < numberOfColumns; i++){
t.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
}
headerRender = (DefaulttableCellRenderer)
t.getTableHeader().getDefaultRenderer();
headerRenderer.setHorizontalAlignment(JLabel.CENTER);
}
In your table model class use html of column name
example:
"<html><center>First column</html>"

Java JTable header word wrap

I am trying to get the header on a table to have word wrap. I have managed to do this but the first data row is expanding. The code for the table is:
public class GenerateTable extends JTable {
private JCheckBox boxSelect = new JCheckBox();
private JTableHeader hdGen;
public class LineWrapCellRenderer extends JTextArea implements TableCellRenderer {
private static final long serialVersionUID = 1L;
int rowHeight = 0; // current max row height for this scan
#Override
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column)
{
/*
* row < 0 means header
*/
if(row >= 0) {
setWrapStyleWord(false);
return this;
}
setText((String) value);
setWrapStyleWord(true);
setLineWrap(true);
// current table column width in pixels
int colWidth = table.getColumnModel().getColumn(column).getWidth();
// set the text area width (height doesn't matter here)
setSize(new Dimension(colWidth, 1));
// get the text area preferred height and add the row margin
int height = getPreferredSize().height + table.getRowMargin();
// ensure the row height fits the cell with most lines, row = -1 for header
if (column == 2 || height > rowHeight) {
table.setRowHeight(row, height);
rowHeight = height;
}
return this;
}
}
LineWrapCellRenderer lwHeader = new LineWrapCellRenderer();
public GenerateTable(GenerateTableModel model) {
super(model);
this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
/*
* Select
*/
TableColumn colSelect = this.getColumnModel().getColumn(0);
colSelect.setCellEditor(new DefaultCellEditor(boxSelect));
colSelect.setPreferredWidth(60);
/*
* category
*/
this.getColumnModel().getColumn(1).setResizable(false);
this.getColumnModel().getColumn(1).setPreferredWidth(200);
/*
* Amount values
*/
for (int i=2;i<model.getColumnCount();i++) {
colSelect = this.getColumnModel().getColumn(i);
colSelect.setPreferredWidth(100);
colSelect.setResizable(false);
colSelect.setHeaderRenderer(lwHeader);
}
}
}
The output is:
I have followed the code through in debug and LineWrapCellRenderer is not being called for the data lines. If I take the code out I get a normal table but no wrap on the header. Is this a recognised problem or am I missing something?
Any help appreciated
You can achieve multi-line headers much easier.
As with many Swing components you can use HTML code. In HTML specify <br> elements to indicate where line breaks / new lines should occur.
For example if you use the following header values (column names):
String[] columnNames = {
"<html>First<br>column</html>",
"<html>Second<br>column</html>",
"<html>Third<br>column</html>"
};
Then the headers will be properly rendered in 2 lines. You don't even need to create/use a custom header renderer, the default header renderer properly handles HTML code.
Note: The header height will be determined by the height of the first column. So you have to use a 2-line HTML value for the first column too. If you only have 1 word for the first column, you may additionally add an empty second line like this: "<html>Select<br> </html>"

How to adjust row width according to data in JTable?

I have a scrollable JTable inside a JDialog and i wish to autoadjust the row width according to data length.
Any ideas?
Use the combination of JTable.setRowHeight method and a cell renderer based on JTextArea
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;

Java JTable setting Column Width

I have a JTable in which I set the column size as follows:
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(400);
This works fine, but when the table is maximized, I get empty space to the right of the last column. Is it possible to make the last column resize to the end of the window when resized?
I found AUTO_RESIZE_LAST_COLUMN property in docs but it does not work.
Edit: JTable is in a JScrollPane its prefered size is set.
What happens if you call setMinWidth(400) on the last column instead of setPreferredWidth(400)?
In the JavaDoc for JTable, read the docs for doLayout() very carefully. Here are some choice bits:
When the method is called as a result of the resizing of an enclosing window, the
resizingColumn is null. This means that resizing has taken place "outside" the JTable
and the change - or "delta" - should be distributed to all of the columns regardless of
this JTable's automatic resize mode.
This might be why AUTO_RESIZE_LAST_COLUMN didn't help you.
Note: When a JTable makes adjustments to the widths of the columns it respects their
minimum and maximum values absolutely.
This says that you might want to set Min == Max for all but the last columns, then set Min = Preferred on the last column and either not set Max or set a very large value for Max.
With JTable.AUTO_RESIZE_OFF, the table will not change the size of any of the columns for you, so it will take your preferred setting. If it is your goal to have the columns default to your preferred size, except to have the last column fill the rest of the pane, You have the option of using the JTable.AUTO_RESIZE_LAST_COLUMN autoResizeMode, but it might be most effective when used with TableColumn.setMaxWidth() instead of TableColumn.setPreferredWidth() for all but the last column.
Once you are satisfied that AUTO_RESIZE_LAST_COLUMN does in fact work, you can experiment with a combination of TableColumn.setMaxWidth() and TableColumn.setMinWidth()
JTable.AUTO_RESIZE_LAST_COLUMN is defined as "During all resize operations, apply adjustments to the last column only" which means you have to set the autoresizemode at the end of your code, otherwise setPreferredWidth() won't affect anything!
So in your case this would be the correct way:
table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(400);
table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
Use this method
public static void setColumnWidths(JTable table, int... widths) {
TableColumnModel columnModel = table.getColumnModel();
for (int i = 0; i < widths.length; i++) {
if (i < columnModel.getColumnCount()) {
columnModel.getColumn(i).setMaxWidth(widths[i]);
}
else break;
}
}
Or extend the JTable class:
public class Table extends JTable {
public void setColumnWidths(int... widths) {
for (int i = 0; i < widths.length; i++) {
if (i < columnModel.getColumnCount()) {
columnModel.getColumn(i).setMaxWidth(widths[i]);
}
else break;
}
}
}
And then
table.setColumnWidths(30, 150, 100, 100);
Reading the remark of Kleopatra (her 2nd time she suggested to have a look at javax.swing.JXTable, and now I Am sorry I didn't have a look the first time :) )
I suggest you follow the link
I had this solution for the same problem: (but I suggest you follow the link above)
On resize the table, scale the table column widths to the current table total width.
to do this I use a global array of ints for the (relative) column widths):
private int[] columnWidths=null;
I use this function to set the table column widths:
public void setColumnWidths(int[] widths){
int nrCols=table.getModel().getColumnCount();
if(nrCols==0||widths==null){
return;
}
this.columnWidths=widths.clone();
//current width of the table:
int totalWidth=table.getWidth();
int totalWidthRequested=0;
int nrRequestedWidths=columnWidths.length;
int defaultWidth=(int)Math.floor((double)totalWidth/(double)nrCols);
for(int col=0;col<nrCols;col++){
int width = 0;
if(columnWidths.length>col){
width=columnWidths[col];
}
totalWidthRequested+=width;
}
//Note: for the not defined columns: use the defaultWidth
if(nrRequestedWidths<nrCols){
log.fine("Setting column widths: nr of columns do not match column widths requested");
totalWidthRequested+=((nrCols-nrRequestedWidths)*defaultWidth);
}
//calculate the scale for the column width
double factor=(double)totalWidth/(double)totalWidthRequested;
for(int col=0;col<nrCols;col++){
int width = defaultWidth;
if(columnWidths.length>col){
//scale the requested width to the current table width
width=(int)Math.floor(factor*(double)columnWidths[col]);
}
table.getColumnModel().getColumn(col).setPreferredWidth(width);
table.getColumnModel().getColumn(col).setWidth(width);
}
}
When setting the data I call:
setColumnWidths(this.columnWidths);
and on changing I call the ComponentListener set to the parent of the table (in my case the JScrollPane that is the container of my table):
public void componentResized(ComponentEvent componentEvent) {
this.setColumnWidths(this.columnWidths);
}
note that the JTable table is also global:
private JTable table;
And here I set the listener:
scrollPane=new JScrollPane(table);
scrollPane.addComponentListener(this);
This code is worked for me without setAutoResizeModes.
TableColumnModel columnModel = jTable1.getColumnModel();
columnModel.getColumn(1).setPreferredWidth(170);
columnModel.getColumn(1).setMaxWidth(170);
columnModel.getColumn(2).setPreferredWidth(150);
columnModel.getColumn(2).setMaxWidth(150);
columnModel.getColumn(3).setPreferredWidth(40);
columnModel.getColumn(3).setMaxWidth(40);
fireTableStructureChanged();
will default the resize behavior ! If this method is called somewhere in your code AFTER you did set the column resize properties all your settings will be reset. This side effect can happen indirectly. F.e. as a consequence of the linked data model being changed in a way this method is called, after properties are set.
No need for the option, just make the preferred width of the last column the maximum and it will take all the extra space.
table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(Integer.MAX_INT);
Use this code. It worked for me. I considered for 3 columns. Change the loop value for your code.
TableColumn column = null;
for (int i = 0; i < 3; i++) {
column = table.getColumnModel().getColumn(i);
if (i == 0)
column.setMaxWidth(10);
if (i == 2)
column.setMaxWidth(50);
}

Categories