Showing posts with label JScrollbar. Show all posts
Showing posts with label JScrollbar. Show all posts

Tuesday, January 7, 2014

Make JTable show horizontal scroll bar and automatically resize to the width of the container

It will be nice that when the frame is small, we can use the scroll bar to view the contents of the JTable and when the frame is larger than the JTable size, the table is able to automatically fill up the space. This can be achieved by the following methods

1. Override the method getScrollableTracksViewportWidth() and set the table's auto resize mode to AUTO_RESIZE_OFF.


          JTable table = new JTable() {
                private boolean doingLayout;

                public boolean getScrollableTracksViewportWidth() {
                        return getPreferredSize().width < getParent().getWidth();
                }

        public void doLayout() {
           if (getScrollableTracksViewportWidth()) {
          
               autoResizeMode = AUTO_RESIZE_SUBSEQUENT_COLUMNS;
           }
           doingLayout = true;
           super.doLayout();
           doingLayout = false;
           autoResizeMode = AUTO_RESIZE_OFF;
       }
       public void columnMarginChanged(ChangeEvent e) {
           if (isEditing()) {
               removeEditor();
           }
           TableColumn resizingColumn = getTableHeader().getResizingColumn();
           // Need to do this here, before the parent's
           // layout manager calls getPreferredSize().
           if (resizingColumn != null && autoResizeMode == AUTO_RESIZE_OFF
                   && !doingLayout) {
               resizingColumn.setPreferredWidth(resizingColumn.getWidth());
           }
           resizeAndRepaint();
       }
         }

         table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
         JScrollPane scrollPane = new JScrollPane(table);
         frame.getContentPane.add(scrollPane);

2. Use a ComponentListener to toggle the auto resize mode of the JTable between AUTO_RESIZE_OFF and AUTO_RESIZE_ALL_COLUMNS.


    table.getParent().addComponentListener(new ComponentAdapter() {
        public void componentResized(final ComponentEvent e) {
            if (jTable.getPreferredSize().width < jTable.getParent().getWidth()) {
                 jTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
            } else {
                jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            }
        }
   });
-------------------------------------------------------------------------
                        
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.
-----------------------------------------------------------------------------

References:

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.

JTable freezing/fixing columns when scrolling

Following is the sample code for freezing one or more table columns while scrolling through the other columns.

import java.awt.Dimension;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

public class TestClass extends javax.swing.JFrame {
    private DefaultTableModel tableModel;
    private javax.swing.JScrollPane jScrollPane;
    private javax.swing.JTable jTable;
    private javax.swing.JTable freezeTable;
    private int fixedColumns = 1;//number of colums to be freezed
 
    public TestClass() {
        jScrollPane = new javax.swing.JScrollPane();
        jTable = new javax.swing.JTable();
        jScrollPane.setViewportView(jTable);
        getContentPane().add(jScrollPane);
     
        setPreferredSize(new Dimension(300,200));  
        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"}};
        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);
        jTable.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent e) {
                //  Keep freezeTable in sync with the jTable
                if ("selectionModel".equals(e.getPropertyName())) {
                    freezeTable.setSelectionModel(jTable.getSelectionModel());
                }

                if ("dataModel".equals(e.getPropertyName())) {
                    freezeTable.setModel(jTable.getModel());
                }
            }
        });
     
        freezeTable = new javax.swing.JTable();
        freezeTable.setAutoCreateColumnsFromModel(false);
        freezeTable.setModel(tableModel);
        freezeTable.setSelectionModel(jTable.getSelectionModel());
        freezeTable.setFocusable(false);
     
        for (int i = 0; i < fixedColumns; i++) {
            TableColumnModel colModel = jTable.getColumnModel();
            TableColumn column = colModel.getColumn(0);
            colModel.removeColumn(column);
            freezeTable.getColumnModel().addColumn(column);
        }

        //Synchronize sorting of freezeTable with jTable
        jTable.setAutoCreateRowSorter(true);
        freezeTable.setRowSorter(jTable.getRowSorter());
        jTable.setUpdateSelectionOnSort(true);
        freezeTable.setUpdateSelectionOnSort(false);

        //  Add the fixed table to the scroll pane
        freezeTable.setPreferredScrollableViewportSize(freezeTable.getPreferredSize());
        jScrollPane.setRowHeaderView(freezeTable);
        jScrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, freezeTable.getTableHeader());

        // Synchronize scrolling of the row header with the jTable
        jScrollPane.getRowHeader().addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                //  Sync the scroll pane scrollbar with the row header
                JViewport viewport = (JViewport) e.getSource();
                jScrollPane.getVerticalScrollBar().setValue(viewport.getViewPosition().y);
            }
        });
        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 column headers while 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.

Friday, December 13, 2013

JTable automatically scroll cell to view when tabbing out of view

/**
     * When tabbing out of the view, scroll the selected cell to the closest edge of the view.
     * If a tab or mouse click is within the view, no scroll will happen
     * @param rowIndex the row of the selected cell
     * @param vColIndex the column of the selected cell
     */
    public void scrollCellToView(int rowIndex, int vColIndex) {
        if (!(this.getParent() instanceof JViewport)) {
            return;
        }
        JViewport viewport = (JViewport) this.getParent();
        Rectangle rect = this.getCellRect(rowIndex, vColIndex, true);
        Rectangle viewRect = viewport.getViewRect();
     
        int x = viewRect.x;
        int y = viewRect.y;
     
        if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){
         
        } else if (rect.x < viewRect.x){
            x = rect.x;
        } else if (rect.x > (viewRect.x + viewRect.width - rect.width)) {
            x = rect.x - viewRect.width + rect.width;
        }
     
        if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){
         
        } else if (rect.y < viewRect.y){
            y = rect.y;
        } else if (rect.y > (viewRect.y + viewRect.height - rect.height)){
            y = rect.y - viewRect.height + rect.height;
        }
     
        viewport.setViewPosition(new Point(x,y));
    }

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

                        
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.