我有一个 JFrame,其中多个相似宽度的 JPanel 彼此对齐。我使用其中一个 JPanel 来显示一个 JTable,它是该批次的最后一个 JPanel。这个 JPanel 有一个 JScrollpane 作为子组件。这是我尝试动态添加表格的地方。此 JScrollpane 的初始高度设置为 40。
我使用 Netbeans 6.8 设计了上面的模板
现在我正在尝试将表添加到 JPanel。当按下代码片段下方的按钮时,将被调用。包含此代码的类扩展了 javax.swing.JFrame 类。
我期望下面的代码会根据行数调整表格高度并显示表格。
SearchTable = new JTable(RowData, DisplayNames) {
@Override
public boolean isCellEditable(int rowIndex, int vColIndex) {
return false;
}
};
// if row count is less than 10 then display all the rows without a scroll bar
if (SearchTable.getRowCount() < 10) {
pnl_tblpanel.setPreferredSize(new Dimension(625, SearchTable.getRowHeight() * (SearchTable.getRowCount() + 4)));
scr_tblholder.setPreferredSize(new Dimension(625, SearchTable.getRowHeight() * (SearchTable.getRowCount() + 4)));
} else {// if row count is more than 10 display first 10 rows and add a scroll bar
pnl_tblpanel.setPreferredSize(new Dimension(625, SearchTable.getRowHeight() * (10 + 2)));
scr_tblholder.setAutoscrolls(true);
}
//pnl_tblpanel.add(scr_tblholder);
scr_tblholder.setViewportView(SearchTable);
//pnl_tblpanel.repaint();
pnl_tblpanel.validate();
this.validate();
//this.repaint();
pnl_tblpanel.setVisible(true);
this.pack();
表格显示,但表格高度不会根据行数更改。它保持其默认值。我一直在尝试验证和重绘的许多组合,但没有任何效果。(更绝望)
任何人都可以对此有所了解吗 谢谢