1

我有一个 JPanel,我在其中添加了一个 JScrollPane(请参阅下面的课程)。我添加了一个 JTextField 来验证一切正常(而不是 JScrollPane),并且文本字段已添加到面板中。当我尝试添加我的 JScrollPane 时,没有显示任何内容(白色背景)。我该如何解决?

protected JPanel createContentPanel() {
    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());

    final String[] columnNames = { "Test1", "Test2", "Test3" };
    final String[][] data = {
            { "foo1", "foo2", "foo3" },
            { "bar1", "bar2", "bar3" },
            { "bar1", "bar2", "bar3" },
            { "bar1", "bar2", "bar3" },
            { "bar1", "bar2", "bar3" },
            { "bar1", "bar2", "bar3" },
            { "bar1", "bar2", "bar3" },
            { "bar1", "bar2", "bar3" }
    };

    ScrollableTable scrollableTablePane = new ScrollableTable(data, columnNames);
    panel.add(scrollableTablePane, BorderLayout.CENTER);
    return panel;
}


public class ScrollableTable extends JScrollPane {

    public ScrollableTable(String[][] aData, String[] aColumnNames) {
        super();

        TableModel model = getTableModel(aData, aColumnNames);
        JTable overviewTable = new JTable(model);
        overviewTable.setGridColor(new Color(240, 240, 240));
        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
        overviewTable.setRowSorter(sorter);

        this.add(overviewTable);
    }

    private TableModel getTableModel(String[][] aData, String[] aColumnNames) {
        TableModel model = new DefaultTableModel(aData, aColumnNames) {
            public Class<?> getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        return model;
    }
}
4

1 回答 1

7

要设置 JScrollPane 的显示组件,请使用JScrollPane#setViewportView(Component)而不是 add(Component)。

public ScrollableTable(String[][] aData, String[] aColumnNames) {
    super();

    TableModel model = getTableModel(aData, aColumnNames);
    JTable overviewTable = new JTable(model);
    overviewTable.setGridColor(new Color(240, 240, 240));
    TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    overviewTable.setRowSorter(sorter);

    this.setViewportView(overviewTable);
}
于 2012-06-10T20:51:33.617 回答