Jtable不显示列标题。我正在使用向量来填充 JTable,但它似乎仍然不起作用。代码如下:
public class InsertFileToJtable extends AbstractTableModel{
Vector data;
Vector columns;
private String[] colNames = {"col1","col2","col3","col4","col5","col6","col7","col8"};
public InsertFileToJtable() {
String line;
data = new Vector();
columns = new Vector();
try {
FileInputStream fis = new FileInputStream("ProcessList.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
while (st1.hasMoreTokens())
columns.addElement(st1.nextToken());
while ((line = br.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line, " ");
while (st2.hasMoreTokens())
data.addElement(st2.nextToken());
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public int getRowCount() {
return data.size() / getColumnCount();
}
public int getColumnCount() {
return columns.size()-1;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return (String) data.elementAt((rowIndex * getColumnCount())
+ columnIndex);
}
@Override
public String getColumnName(int column) {
return colNames[column];
}
@Override
public Class getColumnClass(int col){
return getValueAt(0,col).getClass();
}
}
以下是从 Main 调用该表的方式:
public static void main(String[] args) {
InsertFileToJtable model = new InsertFileToJtable();
JTable table = new JTable(model);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
table.setModel(model);
JScrollPane scrollpane = new JScrollPane(table);
scrollpane.setViewportView(tabbedPane);
tabbedPane.addTab("Process",null,table,"");
model.fireTableStructureChanged();
JPanel panel = new JPanel();
panel.add(scrollpane);
frame.add(panel);
}
由于我是新手,我不知道出了什么问题。任何帮助将不胜感激。谢谢!
仅当表位于 JScrollPane 中时,才会自动添加标头。如果它未包含在滚动窗格中,则必须手动管理标头。在您的代码中,它最初添加到滚动窗格中,但后来再次删除 - 通过将表添加到选项卡式窗格中。可能不是您想要的,而是将滚动窗格添加到选项卡中:
JScrollPane scrollpane = new JScrollPane(table);
//scrollpane.setViewportView(tabbedPane);
tabbedPane.addTab("Process",null,scrollPane,"");
为了使表能够显示其标题,您需要将表添加到滚动窗格中。
您一开始没问题,但后来通过更改滚动窗格的视口将其删除
// This was good
JScrollPane scrollpane = new JScrollPane(table);
// Then you changed it
scrollpane.setViewportView(tabbedPane);
// Then you added it to the tabbed pane
tabbedPane.addTab("Process",null,table,"");
尝试将表添加回滚动窗格,并将其添加到选项卡式窗格