【问题标题】:JTable auto resizing to JScrollPane height and widthJTable 自动调整到 JScrollPane 的高度和宽度
【发布时间】:2026-02-07 00:25:01
【问题描述】:

我一直在阅读整个互联网,试图找到解决问题的方法。 谁能帮我。当滚动条显示的行数不足时,如何自动调整 Jtable 的高度以适合父容器。谢谢

更新:显示我的问题的代码,以及建议的解决方案没有帮助。谢谢

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.JTable;


public class t extends JFrame {

    private JPanel contentPane;
    private JTable table;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    t frame = new t();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public t() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new BorderLayout(0, 0));

        JScrollPane scrollPane = new JScrollPane();
        contentPane.add(scrollPane, BorderLayout.CENTER);

        table = new JTable(10,10);
        table. setFillsViewportHeight( true );
        scrollPane.setViewportView(table);
    }

}

【问题讨论】:

  • 发帖MCVE寻求帮助。
  • “当滚动条显示的行数不足时,如何自动调整 Jtable 的高度以适应父容器。” 这真的没有意义(对于用户),因此是不可取的。
  • @AndrewThompson 不明白为什么会这样。我的 Jtable 在 JScrollPane/JPanel/BorderLayout.CENTER .... 内,当我将应用程序大小调整为全屏时,我的 JTable 下有一个空白空间,这很难看(对用户而言)

标签: java swing jtable jscrollpane


【解决方案1】:

当滚动条显示的行数不足时,如何自动调整 Jtable 的高度以适合父容器。

我想你正在寻找:

table. setFillsViewportHeight( true );

编辑:

但似乎不起作用...

将以下代码行添加到您的示例中:

contentPane.setBackground(Color.RED);
scrollPane.getViewport().setBackground(Color.BLUE);

你会看到一个红色的边框。

然后删除:

table. setFillsViewportHeight( true );

你会看到红色和蓝色,表示桌子高度原来是增加的。

如果您希望看到绘制的空单元格,那么它将无法正常工作。该表只能绘制模型中的内容。如果要绘制更多行数据,则需要向模型添加更多行数据。如果高度降低,您需要从模型中删除数据。

当然,现在您需要跟踪哪些是“有效”数据行,哪些是“填充”数据行。因此,您需要创建一个自定义 TableModel 来管理它。然后,您将向表中添加一个 ComponentListener 以处理表中的高度变化,然后对 TableModel 进行操作。

【讨论】:

  • 对不起,但似乎不起作用...将发布更新以显示其不。谢谢