Saidalo
Saidalo

Reputation: 31

Cannot give prefered size to JTable

I have JTable with date from excel file. I filtered it and inserted filtered data into JTable.

Here is the code of class with JTable:

package convert;

public class Table extends JFrame{

    private static final long serialVersionUID = 1L;
    public Table(Vector<Vector<Object>> data){
        super("Converted Table");
        Vector<Object> head = new Vector<Object>();
        head.clear();
        head.add("Supplier");
        head.add("Invoice number");
        head.add("Arrival date at CC");
        head.add("Part number");
        head.add("Shipment quantity");
        head.add("Shipment CBM");
        head.add("Shipment weight");
        head.add("Container Type");
        head.add("Container/truck number");
        head.add("Current Date");
        head.add("Days in CC");
        DefaultTableModel model = new DefaultTableModel(data,head);
        System.out.println(head);
        System.out.println(data.size());

        JPanel panel = new JPanel();
        getContentPane().add(panel, BorderLayout.NORTH);

        JScrollPane scrollPane_1 = new JScrollPane();
        scrollPane_1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        panel.add(scrollPane_1);
        JTable table = new JTable();
        table.setColumnSelectionAllowed(true);
        table.setCellSelectionEnabled(true);
        scrollPane_1.setViewportView(table);
        table.setModel(model);

        for(int i=0;i<11;i++)
        {
            table.getColumnModel().getColumn(i).setPreferredWidth(230);
            table.getColumnModel().getColumn(i).setWidth(230);
        }
    }
 }

Upvotes: 0

Views: 49

Answers (1)

Sergiy Medvynskyy
Sergiy Medvynskyy

Reputation: 11327

To get the correct column widths you need to turn off the auto resizing

table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

Also you should remove the line

table.getColumnModel().getColumn(i).setWidth(230);

setPreferredWidth(230) is enough.

Upvotes: 1

Related Questions