JTable中没有标题

时间:2012-09-23 10:56:54

标签: java swing jtable jscrollpane jtableheader

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);
    }

作为一个新手,我不知道什么是错的。任何帮助将受到高度赞赏。谢谢!

2 个答案:

答案 0 :(得分:6)

仅当表位于JScrollPane中时,才会自动添加标头。如果它不包含在scrollPane中,则必须手动管理标题。在您的代码中,它最初添加到scrollPane,但稍后再次删除 - 通过将表添加到tabbedPane。可能不是你想要的,而是将scrollPane添加到选项卡:

JScrollPane scrollpane = new JScrollPane(table);
//scrollpane.setViewportView(tabbedPane);
tabbedPane.addTab("Process",null,scrollPane,"");

答案 1 :(得分:5)

为了使表能够显示它的标题,您需要将表添加到滚动窗格。

你开始没问题,但后来通过更改滚动窗格的视口

删除了它
// 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,"");

尝试将表格添加回滚动窗格并将其添加到选项卡式窗格