如何在客户端首选大小更改时显示JScrollPane滚动条?

时间:2015-06-27 21:49:49

标签: java swing jtable

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

下面的代码将显示JTable的首选大小更改,但JScrollPane不会添加滚动条。

这是我的SSCCE ......虽然“正确”的部分有问题:

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 个答案:

答案 0 :(得分:2)

两件事

  1. 您应在添加JTable
  2. 时将JScrollPane添加到相框中
  3. 您应该尝试使用setAutoResizeModel上的JTable并将其设置为AUTO_RESIZE_OFF
  4. 像...一样的东西。

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