当前位置: 首页 > 面试题库 >

调整JTable的大小以适合行数

公良鸿禧
2023-03-14
问题内容

我有一个JTable动态填充的表格,我希望表格始终调整大小以适合行数。我不希望任何滚动,因为表格位于面板中,并且面板的内容需要打印。我已经试过了:

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){}
    }
}

问题答案:

我认为这不是最好的方法。但是正如您所坚持的,我将代码放在下面。

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                   
}


 类似资料:
  • 问题内容: 有人问过类似的问题,但是解决方案确实与我正在尝试做的事情相吻合。基本上,我有一篇标题为()的文章。我不想控制标题的长度,但是我也不想标题显示在多行上。CSS或jQuery是否可以根据标签的宽度来调整文本大小? 我知道如果可以检测到文本与边缘的重叠,我将如何处理伪代码: 如果有一个CSS属性,我可以设置为更好,但是我似乎找不到(在这种情况下,溢出不会起作用)。 问题答案: CSS否,Ja

  • 问题内容: 我正在尝试从目录加载图像并将其作为图标放置在中。但是,当图像尺寸很大时,就不能完全放入标签中。我尝试调整图像的大小以适合标签,但无法正常工作。我可以知道我要去哪里了吗? 问题答案: BufferedImage img = ImageIO.read(…); Image scaled = img.getScaledInstance(500, 500, Image.SCALE_SMOOTH)

  • 问题内容: 我正在尝试使图片适合JLabel。我希望将图片尺寸减小到更适合我的Swing JPanel。 我尝试使用setPreferredSize,但是它不起作用。 我想知道是否有一种简单的方法?我应该为此缩放图像吗? 问题答案: 大纲 这是要遵循的步骤。 将图片读取为BufferedImage。 将BufferedImage的大小调整为另一个JLabel大小的BufferedImage。 从调

  • 问题内容: 我正在生成一个文档,就像下面的代码一样,当然,表的内容是变化的。我需要做的是确保无论单元格中的内容量如何,该表的大小都不会超过一页。有办法吗? 编辑:@Bruno Lowagie。模板中包裹着图像的提示听起来很合适,我根据更改了代码,但是现在得到的只是一个空的PDF。我是在做错什么,还是这是完全错误的方法? 问题答案: 如果要使表格适合页面,则应在考虑页面大小之前创建表格,并像Tabl

  • 问题内容: 如何自动缩放HTML5 元素以适合页面? 例如,我可以通过将和属性设置为100%来缩放,但是不会缩放吗? 问题答案: 我相信我已经找到了一个优雅的解决方案: JavaScript CSS 到目前为止,对我没有太大的负面性能影响。

  • 下面是“DisplayImage”自定义面板相关部分的代码: