我有一个JPanel,我在其中添加了一个JScrollPane(参见下面的课程)。我添加了一个JTextField来验证一切正常(而不是JScrollPane)并且文本字段已添加到Panel中。当我尝试添加我的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;
}
}
答案 0 :(得分:6)
要设置JScrollPane的显示组件,请使用JScrollPane#setViewportView(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);
}