当客户端的首选大小发生变化时,如何让 JScrollPane 滚动条出现?

how to get JScrollPane scrollbars to appear when client's preferred size changes?

更改 JScrollPane 中 JTable 的首选大小时,即使为垂直和水平滚动条设置了 AS_NEEDED 策略,JScrollPane 也不会适当更新其滚动条。如何让滚动窗格更新其滚动条?

下面的代码将显示 JTable 的首选大小发生变化,但 JScrollPane 永远不会添加滚动条。

这是我的 SSCCE...尽管 "correct" 部分有问题:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;

public class jTableResizeWidthInScrollPane {
    public static void main( String[] args ) {
        JFrame frame = new JFrame();
        JScrollPane scrollPane = new JScrollPane();
        JTable table = new JTable();
        final TimesTableModel timesTableModel = new TimesTableModel();
        JTextField textField = new JTextField();
        textField.addActionListener(new ActionListener() {
            public void actionPerformed( ActionEvent ae ) {
                timesTableModel.setMaxNumber(Integer.parseInt(textField.getText()));
                SwingUtilities.invokeLater( new Runnable() {
                    public void run() {
                        table.revalidate();
                        System.out.println(
                            "preferred width: "+
                            table.getPreferredSize().getWidth()
                        );
                    }
                });
            }
        });
        table.setModel(timesTableModel);
        scrollPane.setViewportView(table);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        frame.setLayout(new BorderLayout());
        frame.add(textField,BorderLayout.NORTH);
        frame.add(table,BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }
    public static class TimesTableModel extends AbstractTableModel {

        private int max = 10;

        public int getRowCount() {
            return max;
        }

        public int getColumnCount() {
            return max;
        }

        public void setMaxNumber( int max ) {
            this.max = max;
            fireTableStructureChanged();
        }

        public Object getValueAt(int row, int col) {
            return (row+1)*(col+1);
        }

        @Override
        public String getColumnName(int col) {
            return String.valueOf(col);
        }

    }
}

两件事

  1. 当您应该添加 JScrollPane
  2. 时,您将 JTable 添加到框架中
  3. 您应该尝试在 JTable 上使用 setAutoResizeModel 并将其设置为 AUTO_RESIZE_OFF

类似...

table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
frame.add(scrollPane, BorderLayout.CENTER);