Auto resizing the JTable column widths
You can try the next:
public void resizeColumnWidth(JTable table) {
final TableColumnModel columnModel = table.getColumnModel();
for (int column = 0; column < table.getColumnCount(); column++) {
int width = 15; // Min width
for (int row = 0; row < table.getRowCount(); row++) {
TableCellRenderer renderer = table.getCellRenderer(row, column);
Component comp = table.prepareRenderer(renderer, row, column);
width = Math.max(comp.getPreferredSize().width +1 , width);
}
if(width > 300)
width=300;
columnModel.getColumn(column).setPreferredWidth(width);
}
}
This needs to be executed before the resize method.
If you have:
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
Automatically adjust Jtable Column to fit content
If you can use an extra library, try Swingx (https://java.net/projects/swingx)
There you have a JXTable, with a method "packAll()", that does exactly what you are asking for
Auto resize the widths of JTable's columns dynamically
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 );
}
How to resize jTable to fit their contents including its header?
In my code all the columns are arranging only based on header values
Well, I would guess you only invoke your code when the row count is 0.
Check out the Table Column Adjuster for a class to calculate column widths. The code can be invoked dynamically as you add/remove rows of data or change the data in a cell.
How to auto-resize all columns of a JTable to the same size?
You need some way to update the column model when the table changes size.
This basic example uses the invaldiate
method to update it's column model. It also sets the columns as "not" resizable.
This also overrides the tables getScrollableTracksViewportWidth
method to ensure that the table automatically fills the horizontal space. This does mean that it will never display a horizontal scroll bar though.
public class SpringTable extends JTable {
public SpringTable(TableModel dm) {
super(dm);
setAutoResizeMode(AUTO_RESIZE_OFF);
}
public SpringTable() {
setAutoResizeMode(AUTO_RESIZE_OFF);
}
@Override
public void doLayout() {
int width = getWidth();
int columnCount = getColumnCount();
int columnSize = width / columnCount;
for (int index = 0; index < columnCount; index++) {
TableColumn column = getColumnModel().getColumn(index);
column.setResizable(false);
column.setPreferredWidth(width);
}
super.doLayout();
}
@Override
public boolean getScrollableTracksViewportWidth() {
return true;
}
}
It may be better to use doLayout
instead on invalidate
, but you should have a play and see what meets your needs
Running example
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
public class TestJTable {
public static void main(String[] args) {
new TestJTable();
}
public TestJTable() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
List<Pet> pets = new ArrayList<>(25);
pets.add(new Pet("Tyrannosauridae", "TYRANNOSAURUS", 20, 35));
pets.add(new Pet("Dromaeosauridae", "VELOCIRAPTOR", 45, 90));
pets.add(new Pet("Ceratopsidae", "TRICERATOPS", 15, 30));
pets.add(new Pet("Stegosauridae", "STEGOSAURUS", 22, 25));
pets.add(new Pet("Titanosauridae", "MALAWISAURUS", 22, 25));
pets.add(new Pet("Compsognathidae", "COMPSOGNATHUS", 8, 25));
pets.add(new Pet("Brachiosauridae", "BRACHIOSAURUS", 8, 25));
pets.add(new Pet("Diplodocidae", "DIPLODOCUS", 8, 25));
final PetTableModel model = new PetTableModel(pets);
final JTable table = new SpringTable(model);
InputMap im = table.getInputMap(JTable.WHEN_FOCUSED);
ActionMap am = table.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete");
am.put("delete", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
int[] indicies = table.getSelectedRows();
int[] mapped = new int[indicies.length];
for (int index = 0; index < indicies.length; index++) {
mapped[index] = table.convertRowIndexToModel(indicies[index]);
}
model.removePets(mapped);
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class SpringTable extends JTable {
public SpringTable(TableModel dm) {
super(dm);
setAutoResizeMode(AUTO_RESIZE_OFF);
}
public SpringTable() {
setAutoResizeMode(AUTO_RESIZE_OFF);
}
@Override
public void doLayout() {
int width = getWidth();
int columnCount = getColumnCount();
int columnSize = width / columnCount;
for (int index = 0; index < columnCount; index++) {
TableColumn column = getColumnModel().getColumn(index);
column.setResizable(false);
column.setPreferredWidth(width);
}
super.doLayout();
}
@Override
public boolean getScrollableTracksViewportWidth() {
return true;
}
}
public class PetTableModel extends AbstractTableModel {
private List<Pet> pets;
public PetTableModel() {
pets = new ArrayList<>(25);
}
public PetTableModel(List<Pet> pets) {
this.pets = pets;
}
@Override
public int getRowCount() {
return pets.size();
}
public void removePets(int... indicies) {
List<Pet> old = new ArrayList<>(indicies.length);
for (int index : indicies) {
old.add(pets.get(index));
}
for (Pet pet : old) {
int index = pets.indexOf(pet);
pets.remove(pet);
fireTableRowsDeleted(index, index);
}
}
@Override
public Class<?> getColumnClass(int columnIndex) {
Class clazz = String.class;
switch (columnIndex) {
case 2:
case 3:
clazz = Float.class;
}
return clazz;
}
@Override
public String getColumnName(int column) {
String name = "??";
switch (column) {
case 0:
name = "Breed";
break;
case 1:
name = "Category";
break;
case 2:
name = "Buy Price";
break;
case 3:
name = "Sell Price";
break;
}
return name;
}
@Override
public int getColumnCount() {
return 4;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Pet pet = pets.get(rowIndex);
Object value = null;
switch (columnIndex) {
case 0:
value = pet.getBreed();
break;
case 1:
value = pet.getCategory();
break;
case 2:
value = pet.getBuyPrice();
break;
case 3:
value = pet.getSellPrice();
break;
}
return value;
}
public void add(Pet pet) {
pets.add(pet);
fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1);
}
}
public class Pet {
private String breed;
private String category;
private float buyPrice;
private float sellPrice;
public Pet(String breed, String category, float buyPrice, float sellPrice) {
this.breed = breed;
this.category = category;
this.buyPrice = buyPrice;
this.sellPrice = sellPrice;
}
public String getBreed() {
return breed;
}
public float getBuyPrice() {
return buyPrice;
}
public String getCategory() {
return category;
}
public float getSellPrice() {
return sellPrice;
}
}
}
Real Time jTable column resizing
You can use the Table Column Adjuster.
It will adjust the column width based on the size of the header the cell data or both.
Limiting the column width in a JTable, but preserving the ability to expand the column
with table.getColumnModel().getColumn(i).setWidth(100);
you would set the column at i to the size of 100 pixels. if the string is too long, it will be visually cut , but the content can still be viewed by expanding the column.
Resizing JTable columns automatically based on text size
I think that by defalut is there 80pixels, but you can change that with follows, for example ...
TableColumnModel tcm = myTable.getColumnModel();
tcm.getColumn(0).setPreferredWidth(100); //Name
tcm.getColumn(1).setPreferredWidth(40); //Title
tcm.getColumn(2).setPreferredWidth(400); //Surname
tcm.getColumn(3).setPreferredWidth(40); //ID
EDIT
to your second question is better look here, please there are lots of usefull examples about TableColumn
JTable resize only selected column when container size changes
Override the doLayout()
method to intercept the layout. This gives the basics. You will need to determine what you want to do when the last column width is about to go negative.
import javax.swing.*;
import javax.swing.table.*;
public class Test2Table
{
private static Object[][] data = new Object[][]
{
{ "a", "b", "c" },
{ "d", "e", "f" }
};
private static Object[] colNames = new Object[] { "1", "2", "3" };
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run() {
JTable table = new JTable(data, colNames)
{
@Override
public void doLayout()
{
// Viewport size changed. Change last column width
if (tableHeader != null
&& tableHeader.getResizingColumn() == null)
{
TableColumnModel tcm = getColumnModel();
int delta = getParent().getWidth() - tcm.getTotalColumnWidth();
TableColumn last = tcm.getColumn(tcm.getColumnCount() - 1);
last.setPreferredWidth(last.getPreferredWidth() + delta);
last.setWidth(last.getPreferredWidth());
}
else
{
super.doLayout();
}
}
};
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.pack();
frame.setVisible(true);
}
});
}
}
Related Topics
Information About _Java_Options
Mockito: Mock Private Field Initialization
Java Type Generic as Argument for Gson
What Does Maven Update Project Do in Eclipse
Count Int Occurrences with Java8
JPA Query.Getresultlist() - Use in a Generic Way
Why Would One Declare a Java Interface Method as Abstract
Java: Infinite Loop Using Scanner In.Hasnextint()
How to Convert a Java Object to Xml with Open Source APIs
Parsing a Hexadecimal String to an Integer Throws a Numberformatexception
How to Change the Name of a Java Application Process
How to Create a Delay in Swing
Random Number with Probabilities
Why Do I Need a Functional Interface to Work with Lambdas