JTable可水平滚动并增长以填充父容器

时间:2013-01-17 23:57:56

标签: java swing user-interface jtable jscrollpane

我想在JTable中添加JScrollPane并希望它:

  • 可水平和垂直滚动(仅当内容使其大于父容器时)
  • 如果需要(双向)自动增长以填充父容器
  • 在需要时只有/两个滚动条

JList的行为与此完全相同,顺便说一下。但我发现没有简单的方法可以同时使用JTable完成所有目标。完成第一个的简单方法是禁用自动调整大小,但这会阻止第二个发生。我想出了一个非常hacky的解决方案,它将一个组件监听器添加到JScrollPane的父容器中,并在调整该容器大小时调整表的大小。但是,我必须在resize方法中添加一些“软糖因子”(参见4x注释),用小像素量来改变我的高度/宽度检查,因为我猜想有些固有的不准确性。如果没有这些软糖因素,滚动条会显得太快(在需要它们之前),或者即使滚动条存在,长表格单元格的末端也会被切断。关于这些hacky软糖因素最糟糕的部分是,如果你改变了GUI的外观和感觉,那么整个解决方案就会彻底停止工作(即软糖因素需要改变)。这显然远非理想。

必须有一种更清洁的方法来实现这一目标。有人可以帮忙吗?运行附加的代码并拖动整个框架的大小以查看表更新。这段代码使用的金属外观和感觉似乎适用于我的Windows 7机器,并选择了软糖因子,但如果它在另一个操作系统上不能干净利用,我也不会感到惊讶。

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

public class JTableScrollTest {

    private JFrame frame;
    private JPanel panel;
    private DefaultTableModel tableModel;
    private JTable table;
    private JScrollPane scrollPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
        } catch (Throwable e) {
            e.printStackTrace();
        }

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JTableScrollTest window = new JTableScrollTest();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public JTableScrollTest() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panel = new JPanel();
        frame.getContentPane().add(panel, BorderLayout.CENTER);
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        scrollPane = new JScrollPane();
        panel.add(scrollPane);

        tableModel = new DefaultTableModel(new Object[]{"Stuff"},0);
        tableModel.addRow(new Object[]{"reeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeally long string"});
        tableModel.addRow(new Object[]{"a"});
        tableModel.addRow(new Object[]{"a"});
        tableModel.addRow(new Object[]{"a"});
        tableModel.addRow(new Object[]{"a"});
        tableModel.addRow(new Object[]{"a"});
        tableModel.addRow(new Object[]{"a"});
        tableModel.addRow(new Object[]{"a"});
        tableModel.addRow(new Object[]{"a"});
        tableModel.addRow(new Object[]{"a"});
        tableModel.addRow(new Object[]{"a"});
        tableModel.addRow(new Object[]{"a"});
        tableModel.addRow(new Object[]{"LAST ITEM"});
        table = new JTable(tableModel);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        scrollPane.setViewportView(table);

        resizeTable();
        panel.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent evt) {
                resizeTable();
            }
        });
    }

    public void resizeTable() {
        int width = 0;
        int height = 0;
        for (int row = 0; row < table.getRowCount(); row++) {
            TableCellRenderer renderer = table.getCellRenderer(row, 0);
            Component comp = table.prepareRenderer(renderer, row, 0);
            width = Math.max (comp.getPreferredSize().width, width);
            height += comp.getPreferredSize().height;
        }
        if (width > panel.getWidth() - 2) { // fudge factor
            width += 4; // fudge factor
            scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        } else {
            width = panel.getWidth();
            scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        }
        if (height > panel.getHeight() + 4) { // fudge factor
            height -= 26; // fudge factor
            scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        } else {
            height = panel.getHeight();
            scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
        }
        table.setPreferredSize(new Dimension(width, height));
    }
}

1 个答案:

答案 0 :(得分:2)

我有同样的问题。该表只是使列更大或更小,而不是显示滚动条。通过反复试验,我提到的黑客是ComponentListener,您附加到ScrollPane

一旦滚动窗格小于表格的首选大小,诀窍是关闭表格的自动调整大小。请注意,您不应直接设置表的首选大小。单独留下来自动计算。如果您需要更大或更小的某些列,请通过列模型设置其宽度(例如table.getColumnModel().getColumn(0).setMaxWidth(25))。

此类还包括另一个TableModelListener,它在将列添加到表中时执行相同的逻辑。

public final class ScrollingTableFix implements ComponentListener {
  private final JTable table;

  public ScrollingTableFix(JTable table, JScrollPane scrollPane) {
    assert table != null;

    this.table = table;

    table.getModel().addTableModelListener(new ColumnAddFix(table, scrollPane));
  }

  public void componentHidden(final ComponentEvent event) {}

  public void componentMoved(final ComponentEvent event) {}

  public void componentResized(final ComponentEvent event) {
    // turn off resize and let the scroll bar appear once the component is smaller than the table
    if (event.getComponent().getWidth() < table.getPreferredSize().getWidth()) {
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    }
    // otherwise resize new columns in the table
    else {
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    }
  }

  public void componentShown(final ComponentEvent event) {}

  // similar behavior is needed when columns are added to the table
  private static final class ColumnAddFix implements TableModelListener {
    private final JTable table;
    private final JScrollPane scrollPane;

    ColumnAddFix(JTable table, JScrollPane scrollPane) {
      this.table = table;
      this.scrollPane = scrollPane;
     }

    @Override
    public void tableChanged(TableModelEvent e) {
      if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
        if (scrollPane.getViewport().getWidth() < table.getPreferredSize().getWidth()) {
          table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        }
        else {
          table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        }
      }
     }
   }
}

要使用它,只需将所有内容连接起来:

JTable table = new JTable();
JScrollPane scroller = new JScrollPane(table);
scroller.addComponentListener(new ScrollingTableFix(table, scroller));