调整JTable的大小以适应行数 [英] Resize JTable to fit number of rows

查看:98
本文介绍了调整JTable的大小以适应行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JTable ,它将动态填充,我希望表总是调整大小以适应行数。我不希望任何滚动,因为表格在面板中,需要打印面板的内容。
我试过这个:

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 is in a panel and the contents of the panel needs to be printed. I've tried this:

Dimension d = itemsTable.getPreferredSize();
    //scrollPane.setPreferredSize(new Dimension(d.width,itemsTable.getRowHeight()*itemsTable.getRowCount()+10));
    itemsTable.setPreferredScrollableViewportSize(new Dimension(d.width,itemsTable.getRowHeight()*itemsTable.getRowCount()+1))

但它似乎不起作用。

public void getDetails(PosView pv){
    Connection con = con();
    DefaultTableModel model = (DefaultTableModel)pv.getItemsTable().getModel();
    String date = null;
    double total = 0.0, paid = 0.0;
    try{
        ps = con.prepareStatement("SELECT DISTINCT AMOUNT_PAYABLE, AMOUNT_PAID, BALANCE, DATE FROM SALES WHERE PAYMENT_ID = ?");
        ps.setString(1, paymentId);
        rs = ps.executeQuery();
        while(rs.next()){
            total = (rs.getDouble(1));
            paid += (rs.getDouble(2));
            date = rs.getString(4);
        }
        double balance = total - paid;
        pv.setDate(date);
        pv.setPaymentId(paymentId);

        ps = con.prepareStatement("SELECT QUANTITY, ITEM_NAME, SELLING_PRICE, TOTAL FROM ITEMS_BOUGHT WHERE ID = ?");
        ps.setString(1, paymentId);
        rs = ps.executeQuery();
        while(rs.next()){
            Object data[] = {rs.getInt(1), rs.getString(2), rs.getDouble(3),rs.getDouble(4)};
            model.addRow(data);
        }

        logActivity(userId, "PAYMENT RECEIPT "+ paymentId +" GENERATED", con);
        pv.setTotal(total);
        pv.setPaid(paid);
        pv.setBalance(balance);
    }catch(SQLException e){
        showMessageDialog(null, e.getMessage());
    }finally{
        try {
            if(ps!=null)
                ps.close();
            con.close();
        }catch(Exception e){}
    }
}


推荐答案

我不认为这是最好的方式。但是你坚持要我把代码放在下面。

I don't think this is the best way. But as you insist i have put the code below.

import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author user
 */
public class MyFrame extends javax.swing.JFrame {

    private DefaultTableModel model = null;

    TableRowSorter<DefaultTableModel> sorter = null;

    /**
     * Creates new form MyFrame
     */
    public MyFrame() {
        initComponents();
        model = new DefaultTableModel(null, new String[]{
            "Name", "age", "salary"
        });
        jTable1.setModel(model);
        for (int i = 0; i < 10; i++) {
            model.addRow(new Object[]{"Beniton", 34, 10000});
            model.addRow(new Object[]{"Joema", 33, 10000});
        }
        sorter = new TableRowSorter<DefaultTableModel>(model);
        jTable1.setRowSorter(sorter);
        int rowCount = model.getRowCount();
        this.setSize(this.getWidth(), 50+ (jTable1.getRowHeight()*(rowCount+1)));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jLabel1 = new javax.swing.JLabel();
        searchBox = new javax.swing.JTextField();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jLabel1.setText("Search");
        getContentPane().add(jLabel1, new java.awt.GridBagConstraints());

        searchBox.setMaximumSize(new java.awt.Dimension(150, 20));
        searchBox.setMinimumSize(new java.awt.Dimension(150, 20));
        searchBox.setName("searchField"); // NOI18N
        searchBox.setPreferredSize(new java.awt.Dimension(150, 20));
        searchBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchBoxActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        getContentPane().add(searchBox, gridBagConstraints);
        searchBox.getAccessibleContext().setAccessibleName("");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        getContentPane().add(jTable1, gridBagConstraints);

        pack();
    }// </editor-fold>                        

    private void searchBoxActionPerformed(java.awt.event.ActionEvent evt) {                                          
        if (searchBox.getText().length() > 0) {
            Integer value = Integer.parseInt(searchBox.getText());
            // Checking the age as Index is 1
            RowFilter<DefaultTableModel, Integer> rf = RowFilter.numberFilter(RowFilter.ComparisonType.BEFORE, value, 1);
            sorter.setRowFilter(rf);
        } else {
            sorter.setRowFilter(null);
        }
    }                                         

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MyFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField searchBox;
    // End of variables declaration                   
}

这篇关于调整JTable的大小以适应行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆