How can i get horizontal scroll bar for a JTable

73 views Asked by At

I have 3 columns for a table, with fixed scroll pane dimensions.

3rd column has data exceeding the column length.

To see the data in column 3 i need to resize the whole window it is embedded in.

Instead i want to have 3 columns stretched to its max data length.

And if this exceeds the dimensions of the scroll pane i would like to have a horizontal scroll bar.

==========

So the 1st thing to achieve is how can i specify "stretch the column to its max data length".

Example Code Without the feature

import java.awt.*;

import javax.swing.*;
import javax.swing.plaf.basic.BasicBorders.MarginBorder;
import javax.swing.plaf.metal.MetalBorders.TableHeaderBorder;
import javax.swing.table.*;
import javax.swing.border.*;

public class TableRowRenderingTip extends JPanel
{
    public TableRowRenderingTip()
    {
        Object[] columnNames = {"Check","Allowed Commands", "Specification", "Description"};
        Object[][] data =
        {
            {Boolean.FALSE, "BASELINE-CONTROL", "WebDav", "Creates a snapshot of version control"},
            {Boolean.FALSE, "CHECKIN", "WebDav", "Checks in a verion controlled Web"},
            {Boolean.FALSE, "CHECKOUT", "WebDav", "Checks out a verion controlled Web"},
            {Boolean.FALSE, "CONNECT", "1.1", "Allow proxies to act as tunnels for"},

        };

        DefaultTableModel model = new DefaultTableModel(data, columnNames)
        {           
            @Override
            public  Class<? extends Object> getColumnClass(int column)
            {
                return getValueAt(0, column).getClass();
            }

            @Override 
            public boolean isCellEditable(int row, int column)
            {
                return column==0;
            }

        };

        add( createData(model) );
    }



    private static JComponent createData(final DefaultTableModel model) 
    {       
        JTable inLineTable = new JTable( model );       
        inLineTable.setPreferredScrollableViewportSize(inLineTable.getPreferredSize());
        inLineTable.setShowGrid(false);
        inLineTable.setShowVerticalLines(false);
        JScrollPane scrollPane = new JScrollPane(inLineTable);
        scrollPane.setSize(10, 10);
        return scrollPane;
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }

    public static void createAndShowGUI()
    {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       
        frame.add( new TableRowRenderingTip() );
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
0

There are 0 answers