简体   繁体   中英

How to resize JTable columns programmatically, DefaultTableModel Java

Because i don't understand the problem i don't know how to ask a good question. But i simply want to resize the columns in JTable. I use JTable and DefaultTableModel class to create the columns, but some columns take to much space, for example check buttons. I wonder if someone knows how to minimize these columns programmatically.

Here is some code i use

public static final String[] COLUMNS = {"Närvaro / Frånvaro", "Deltagare", "Ärendenummer", "Avvikelse"};
private CheckBoxDefaultTableModel model = new CheckBoxDefaultTableModel(COLUMNS, 0);
private final JTable table = new JTable(model);

class CheckBoxDefaultTableModel extends DefaultTableModel {

private List<String> removedItemsList = new ArrayList<String>();

public CheckBoxDefaultTableModel(Object[] columnNames, int rowCount) {
    super(columnNames, rowCount);
}
 Object[] row = {Boolean.FALSE, namn, caseNbr, null};

I don't have reputation to add a picture of my program, but it looks like in this link:

https://www.google.se/search?q=DefaultTableModel+java&es_sm=122&source=lnms&tbm=isch&sa=X&ved=0CAgQ_AUoAmoVChMIx8-2na2uyAIVSY8sCh2KhQ4R&biw=1093&bih=522#tbm=isch&q=DefaultTableModel+java+gui&imgrc=tWPQqLj7FDfIBM%3A

This was needed to resize JTable columns,

TableColumnModel tcm = table.getColumnModel();       
tcm.getColumn(1).setMaxWidth(110);
tcm.getColumn(1).setPreferredWidth(2);

To center a JTable cell value,

DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
table.getColumnModel().getColumn(3).setCellRenderer( centerRenderer );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM