Monday, December 16, 2013

JTable Freezing/Fixing column headers or rows while scrolling


import java.awt.Dimension;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class TestClass extends javax.swing.JFrame {
    private DefaultTableModel tableModel;
    private javax.swing.JScrollPane jScrollPane;
    private javax.swing.JTable jTable;
 
    public TestClass() {
        jScrollPane = new javax.swing.JScrollPane();
        jTable = new javax.swing.JTable();
        jScrollPane.setViewportView(jTable);
        getContentPane().add(jScrollPane);
     
        setPreferredSize(new Dimension(300,120));  
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
        Object[][] data = {{"Item1", "Papaya", "Letus", "Cashew", "Pine"},
                             {"Item2", "Orange", "Carrot", "Pine nut", "Oak"},
                             {"Item3", "Apple", "Pepper", "Pistacho", "Cypress"},
                             {"Item4", "Mango", "Tomato", "Almond", "Cedar"},
                             {"Item5", "Pear", "Romman", "Brazil", "Palm"}};
        Object[] headers = {"Item", "Fruit", "Vegetable", "Nuts", "Tree"};
        tableModel = new DefaultTableModel(data, headers);
        jTable.setModel(tableModel);
     
        jTable.setAutoCreateColumnsFromModel( false );
        for (int i=0; i<jTable.getColumnCount(); i++){
            jTable.getColumnModel().getColumn(i).setMinWidth(100);
        }
        jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        jScrollPane.setColumnHeaderView(jTable.getTableHeader());
     
        pack();
    }
 
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TestClass().setVisible(true);
            }
        });
    }
}

See also
JTable freezing/fixing columns when scrolling

-------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

No comments:

Post a Comment