tags:

views:

85

answers:

1

Hi,

I hava a table in a scrollPane. There are 6 columns in my table. I want the last 2 columns to be wider than other columns. But after I set the size of the columns, the vertical scroll bar disappeared. If I comment out the code for resetting the columns width, everything goes back to normal. Could anyone tell me what's the problem of this? Thanks a lot!!

I copied several related dimentions blow:

table.setPreferredScrollableViewportSize(new Dimension(900, 500));
feedback = new JScrollPane(table);
feedback.setMinimumSize(new Dimension(900, 400));

the code to resize the columns:

TableColumn column = null;
for (int i = 0; i < 6; i++) {
    column = table.getColumnModel().getColumn(i);
    if (i == 4) {
        column.setPreferredWidth(250); //third column is bigger
    } else { 
        if (i==5) {
           column.setPreferredWidth(250);
        }
        else {
            column.setPreferredWidth(100);
        } 
    }
} 
A: 

I am unable to reproduce the problem you describe. It may a problem with your layout, or it may require Setting the Scroll Bar Policy.

import javax.swing.*;
import javax.swing.table.*;

public class TablePanel extends JPanel {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame f = new JFrame("JTable");
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.add(new TablePanel());
                f.pack();
                f.setVisible(true);
            }
        });
    }

    public TablePanel() {
        TableModel dataModel = new MyTableModel();
        JTable table = new JTable(dataModel);
        table.setAutoCreateRowSorter(true);
        table.getColumnModel().getColumn(0).setPreferredWidth(100);
        table.getColumnModel().getColumn(1).setPreferredWidth(150);
        table.getColumnModel().getColumn(2).setPreferredWidth(200);
        JScrollPane jsp = new JScrollPane(table);
        this.add(jsp);
    }

    private static class MyTableModel extends AbstractTableModel {

        @Override
        public int getRowCount() {
            return 30;
        }

        @Override
        public int getColumnCount() {
            return 3;
        }

        @Override
        public Object getValueAt(int row, int col) {
            return Math.pow(row, col + 1);
        }

        @Override
        public Class<?> getColumnClass(int col) {
            return getValueAt(0, col).getClass();
        }
    }
}
trashgod