正确覆盖getPreferredScrollableViewportSize

时间:2017-02-20 00:10:18

标签: java swing jtable jscrollpane preferredsize

我在JScrollPane中有一个JTable,并且我重写了getPreferredScrollableViewportSize以使JScrollPane适合固定数量的表行,允许滚动条在需要时出现。 我还使用在SO上找到的代码部分来调整表格列的大小以适应它们的内容。

我遇到的问题是,当我在表中添加更宽的行时,水平JScrollBar不会显示。 我尝试了不同的方法来强制JTable,JViewport和JScrollPane正确更新,调用revalidate()或repaint(),doLayout()等,但我没有成功。

当然我可以回想起JFrame上的pack()方法,但是它会导致整个滚动条的宽度增加,而水平滚动条仍然不会出现。

我缺少什么?

这里有一个MVCE,它只是一个丑陋的玩具示例,但它应该足以复制不需要的行为。

感谢您的帮助!

代码:

import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.*;
public class Main
{
    public static void main (String [] a) {
        SwingUtilities.invokeLater (new Runnable () {
            public void run () {
                initGUI ();
            }
        });
    }
    private static void initGUI () {
        final DataTable table = new DataTable ();
        JPanel container = new JPanel (new BorderLayout (0, 20));
        container.add (new JScrollPane (table));
        container.add (new JButton (new AbstractAction ("Add wider row") {
            public void actionPerformed (ActionEvent e) {
                table.addRow ();
                // some of many useless attempts ...
                // table.resizeColumnWidth ();
                // table.revalidate ();
            }
        }), BorderLayout.SOUTH);
        container.setBorder (new EmptyBorder (10, 10, 10, 10));
        JFrame frame = new JFrame ("Test");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.setResizable (false);
        frame.setContentPane (container);
        frame.setLocationRelativeTo (null);
        frame.pack ();
        frame.setVisible (true);
    }
}
class DataTable extends JTable
{
    private static final int VISIBLE_ROWS = 5;

    DataTable () {
        String [][] data = new String [][] {
            {"SomeText", "SomeText"},
            {"SomeText", "SomeText"},
            {"SomeText", "SomeText"},
            {"SomeText", "SomeText"},
            {"SomeText", "SomeText"},
            {"SomeText", "SomeText"}
        };
        setModel (new DefaultTableModel (data, new String [] {"", ""}) {
            @Override public boolean isCellEditable (int row, int column) {
               return false;
            }
        });
        columnModel.setColumnMargin (20);
        setBorder (null);
        setFocusable (false);
        setRowSelectionAllowed (false);
        setShowGrid (false);
        setTableHeader (null);
        resizeColumnWidth ();
    }
    public void addRow () {
        ((DefaultTableModel) getModel ()).addRow (new String [] {"SomeLongerText", "SomeLongerText"});
    }
    private int calculateColumnWidth (int column) {
        TableColumn tableColumn = columnModel.getColumn (column);
        int width = 0;
        for (int row=0; row<getRowCount(); row++) width = Math.max (prepareRenderer (getCellRenderer (row, column), row, column).getPreferredSize ().width, width);
        return width + getIntercellSpacing ().width;
    }
    @Override public Dimension getPreferredScrollableViewportSize () {
        int columnsWidth = 0;
        for (int column=0; column<getColumnCount (); column++) columnsWidth += calculateColumnWidth (column);
        return new Dimension (columnsWidth, VISIBLE_ROWS * getRowHeight ());
    }
    protected void resizeColumnWidth () {
        for (int column=0; column<getColumnCount (); column++) columnModel.getColumn (column).setPreferredWidth (calculateColumnWidth (column));
    }
}

编辑:

感谢@camickr,我解决了这个问题,设置了所需的自动调整大小模式,并在每次添加行时调用resizeColumnWidth方法。 我已经分开试过了,我不敢相信我没有同时使用它们。)

Hovewer,我发布了更新后的代码,现在效果很好:

import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.*;
public class Main
{
    public static void main (String [] a) {
        SwingUtilities.invokeLater (new Runnable () {
            public void run () {
                initGUI ();
            }
        });
    }
    private static void initGUI () {
        final DataTable table = new DataTable ();
        JPanel container = new JPanel (new BorderLayout (0, 20));
        container.add (new JScrollPane (table));
        container.add (new JButton (new AbstractAction ("Add wider row") {
            public void actionPerformed (ActionEvent e) {
                table.addRow ();
            }
        }), BorderLayout.SOUTH);
        container.setBorder (new EmptyBorder (10, 10, 10, 10));
        JFrame frame = new JFrame ("Test");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.setResizable (false);
        frame.setContentPane (container);
        frame.setLocationRelativeTo (null);
        frame.pack ();
        frame.setVisible (true);
    }
}
class DataTable extends JTable
{
    private static final int VISIBLE_ROWS = 5;

    DataTable () {
        String [][] data = new String [][] {
            {"SomeText", "SomeText"},
            {"SomeText", "SomeText"},
            {"SomeText", "SomeText"},
            {"SomeText", "SomeText"},
            {"SomeText", "SomeText"},
            {"SomeText", "SomeText"}
        };
        setModel (new DefaultTableModel (data, new String [] {"", ""}) {
            @Override public boolean isCellEditable (int row, int column) {
               return false;
            }
        });
        columnModel.setColumnMargin (20);
        setAutoResizeMode (AUTO_RESIZE_OFF);
        setBorder (null);
        setFocusable (false);
        setRowSelectionAllowed (false);
        setShowGrid (false);
        setTableHeader (null);
        resizeColumnWidth ();
    }
    public void addRow () {
        ((DefaultTableModel) getModel ()).addRow (new String [] {"SomeLongerText", "SomeLongerText"});
        resizeColumnWidth ();
    }
    private int calculateColumnWidth (int column) {
        TableColumn tableColumn = columnModel.getColumn (column);
        int width = 0;
        for (int row=0; row<getRowCount(); row++) width = Math.max (prepareRenderer (getCellRenderer (row, column), row, column).getPreferredSize ().width, width);
        return width + getIntercellSpacing ().width;
    }
    @Override public Dimension getPreferredScrollableViewportSize () {
        int columnsWidth = 0;
        for (int column=0; column<getColumnCount (); column++) columnsWidth += calculateColumnWidth (column);
        return new Dimension (columnsWidth, VISIBLE_ROWS * getRowHeight ());
    }
    protected void resizeColumnWidth () {
        for (int column=0; column<getColumnCount (); column++) columnModel.getColumn (column).setPreferredWidth (calculateColumnWidth (column));
    }
}

1 个答案:

答案 0 :(得分:4)

  

当我在表格中添加更宽的行时,水平的JScrollBar不会显示。

只有在使用时才会出现水平滚动条:

setAutoResizeMode( JTable.AUTO_RESIZE_OFF );

所有列都将以其优先大小显示。它们可能小于视口,在这种情况下,您将看到空白区域,或者它们可能更大,在这种情况下您将看到滚动条。

您需要在resizeColumnWidth()中调用ActionListener方法才能显示滚动条。

在TableModel中添加/更改数据时,您还可以查看支持动态列大小计算的Table Column Adjuster