1

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

由于我是新手,我不知道出了什么问题。任何帮助将不胜感激。谢谢!

4

2 回答 2

6

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

JScrollPane scrollpane = new JScrollPane(table);
//scrollpane.setViewportView(tabbedPane);
tabbedPane.addTab("Process",null,scrollPane,"");
于 2012-09-23T11:04:25.813 回答
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,"");

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

于 2012-09-23T11:05:48.877 回答