Resize JTable to fit number of rows

前端 未结 2 1318
伪装坚强ぢ
伪装坚强ぢ 2021-01-29 10:46

I have a JTable which would be populated dynamically and I want the table to always resize to fit the number of rows. I don\'t want any scrolling because the table

2条回答
  •  执念已碎
    2021-01-29 11:09

    Override getPreferredScrollableViewportSize() to return a multiple of the product of line height and row count. Each time a row is added, pack() the enclosing window.

    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import javax.swing.AbstractAction;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    
    /**
     * @see http://stackoverflow.com/a/37343900/230513
     * @see http://stackoverflow.com/a/37318673/230513
     */
    public class Test {
    
        private void display() {
            JFrame f = new JFrame("Test");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            class MyTableModel extends AbstractTableModel {
    
                private int n = 8;
    
                private void addRow() {
                    n++;
                    fireTableRowsInserted(n - 1, n - 1);
                }
    
                @Override
                public int getRowCount() {
                    return n;
                }
    
                @Override
                public int getColumnCount() {
                    return 4;
                }
    
                @Override
                public Object getValueAt(int rowIndex, int colIndex) {
                    return "R" + rowIndex + ":C" + colIndex;
                }
            };
            MyTableModel model = new MyTableModel();
            JTable table = new JTable(model) {
                @Override
                public Dimension getPreferredScrollableViewportSize() {
                    return new Dimension(super.getPreferredSize().width,
                        getRowHeight() * getRowCount());
                }
            };
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            f.add(new JScrollPane(table));
            f.add(new JButton(new AbstractAction("Add Row") {
                @Override
                public void actionPerformed(ActionEvent e) {
                    model.addRow();
                    f.pack();
                }
            }), BorderLayout.SOUTH);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Test()::display);
        }
    }
    

提交回复
热议问题