1

I have made a GUI JTable which displays a database. I have one problem with sizing.

How can I make it so that the columns of the JTable will fill the JScrollPane but if there are a lot of columns in one table for example then it would just keep them default size and let them scroll.

Basically..

If one of the SQL tables don't fill the JTable and don't need scrolling then I want the columns of that JTable to be made bigger so they do fit.

If the SQL JTable does need scrolling then I just want it to be left like that so it needs scrolling.

This is the code I have for making the JTable:

        JPanel panel1 = new JPanel();
        JTable table = new JTable(){
        private static final long serialVersionUID = 1L;

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

        };
        JScrollPane stable = new JScrollPane (table);
        stable.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        stable.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        panel1.add(stable);
Shivam Paw
  • 203
  • 3
  • 14
  • The problem you have is a VERY expensive one. In order to know the column width requirements, you have to check EVERY row, you then need to decide if the total column width is greater then or less then the viewable area and change the `autoResizeMode` on or off, depending on the state you want to make. What happens when the window is resized? Are you going to recalculate the values again? – MadProgrammer Jul 10 '15 at 13:13
  • Maybe something like [this](http://stackoverflow.com/questions/15014950/jtable-horizontal-scrollbar-based-on-width-of-one-column/15015445#15015445) – MadProgrammer Jul 10 '15 at 13:17
  • @MadProgrammer that has a problem when the cell value is null. – Shivam Paw Jul 10 '15 at 14:07
  • A `null` value becomes a default width. Of course, instead of looking for the exact solution which meets you exact requirements, you could be looking for ideas which move you the right direction ;) – MadProgrammer Jul 10 '15 at 23:03

3 Answers3

2

comment following line in your code:

table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

this makes table columns stretch to fill scrollpane's width

stretching columns to fit entire width of table makes it look ugly. instead i suggest to add following features to your table.

http://www.jroller.com/santhosh/entry/jtable_becomes_uglier_with_auto http://www.jroller.com/santhosh/entry/packing_jtable_columns

this makes your jtable look more professional

Santhosh Kumar Tekuri
  • 3,012
  • 22
  • 22
2

To get exactly what you asked for call following method after table is updated with new model:

public static void tweakColumns(JTable table){
    Enumeration<TableColumn> columns = table.getColumnModel().getColumns();

    int required = 0;
    while(columns.hasMoreElements()){
        TableColumn column = columns.nextElement();
        int width = (int)table.getTableHeader().getDefaultRenderer()
                    .getTableCellRendererComponent(table, column.getIdentifier()
                            , false, false, -1, column.getModelIndex()).getPreferredSize().getWidth();
        required += width;
    }

    JViewport viewport = (JViewport)SwingUtilities.getAncestorOfClass(JViewport.class, table);
    int viewportWidth = viewport.getWidth();
    table.setAutoResizeMode(required<viewportWidth ? JTable.AUTO_RESIZE_ALL_COLUMNS : JTable.AUTO_RESIZE_OFF);
}
Santhosh Kumar Tekuri
  • 3,012
  • 22
  • 22
  • You could have to check EVERY row to know for sure you had the maximum required width for any given column, this is a VERY expensive proposition – MadProgrammer Jul 10 '15 at 13:09
  • the above method, is not going through all rows, it is computing width from column name using table header's renderer. so this is not too costly – Santhosh Kumar Tekuri Jul 10 '15 at 13:11
  • But it's the data which you need to know...No point in using a column header which is 100 characters long when the data is only 5...kind of wasteful :P – MadProgrammer Jul 10 '15 at 13:12
  • This works :D Nice job! One problem I've found is that on startup it isn't working for the SHOW TABLES query but if I do that query again it will work. – Shivam Paw Jul 10 '15 at 14:14
  • table must be showing up, when tweakColumns called. on startup, the table might not yet be showing. so viewport's width will be 0 then – Santhosh Kumar Tekuri Jul 10 '15 at 15:30
0
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.table.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class StatusPage extends JPanel
{
    static DefaultTableModel dm;
    JTable table;
    JScrollPane jsp_table;
    static Connection conn;
    static Statement stmt;
    static ResultSet rs;

    public StatusPage(Connection c)
    {
        conn = c;
        String col_name[] = {"S.No.","Book Name","Author Name","ISBN","Available Book","Issue Book","Total Book"};
        dm = new DefaultTableModel(null,col_name);
        table = new JTable(dm);
        table.getTableHeader().setFont( new Font( "Goudy Old Style" , Font.BOLD, 15 ));
                table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                table.getColumnModel().getColumn(0).setPreferredWidth(50);
                table.getColumnModel().getColumn(1).setPreferredWidth(175);
                table.getColumnModel().getColumn(2).setPreferredWidth(175);
                table.getColumnModel().getColumn(3).setPreferredWidth(125);
                table.getColumnModel().getColumn(4).setPreferredWidth(111);
                table.getColumnModel().getColumn(5).setPreferredWidth(90);
                table.getColumnModel().getColumn(6).setPreferredWidth(90);
        jsp_table = new JScrollPane(table);
        jsp_table.setPreferredSize(new Dimension(850, 520));
        addRowTable();
        add(jsp_table);
    }
    public static void addRowTable()
    {
        try
        {
                    int a = dm.getRowCount();
            int i=0;
            while(i<a)
            {
                dm.removeRow(0);
                i++;
            }

            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
            rs = stmt.executeQuery("SELECT * FROM BOOK_TABLE");

            int count = 1;
            while(rs.next())
            {
                String s[] = new String[7];

                s[0] = ""+count;
                s[1] = rs.getString(6);
                s[2] = rs.getString(1);
                s[3] = rs.getString(2);
                s[4] = ""+rs.getInt(4);
                s[5] = ""+rs.getInt(5);
                s[6] = ""+rs.getInt(3);

                count++;

                dm.addRow(s);
            }
        }
        catch(SQLException e)
        {
            e.printStackTrace();
        }
    }
}

Read this code and change your code Because this code work

A.K.
  • 2,284
  • 3
  • 26
  • 35