Так что я читал через Java "How to use Tables", поскольку я пытаюсь реализовать JTable в своей программе. Я хочу, чтобы взять список значений String из базы данных, а затем отсортировать их по именам столбцов и строк. Теперь я знаю, что нет заголовка строки по умолчанию, например, для столбца, поэтому я обошел это, сделав первый столбец «заголовком строки». Поэтому я решил создать пользовательскую модель таблицы для моей Jtable, чтобы отсортировать данные правильно (данные хранятся в векторе векторов строк & имена столбцов/строк в виде векторных строк отдельно), но все, что я запускал в проблемы. Сначала я получал целую кучу массива из ошибок индекса, поэтому я добавил в код, который показал мне, где данные в таблице таблицы были помещены в Jtable. Так вот код из моего JPanel, который инициализирует моего JTableJTable & custom TableModel не работает как ожидалось
//other GUI stuff above: buttons, labels, etc.
Vector<String> tableColNames = new Vector<String>(1);
Vector<String> tableRowNames = new Vector<String>(1);
Vector<Vector<String>> tableData = new Vector<Vector<String>>(1,1); //<row, col>
for(int i = 0; i <50; i++){
tableData.insertElementAt(new Vector<String>(), i);
for(int b = 0; b<5; b++){
tableData.elementAt(i).insertElementAt("TestData", b);
}
tableRowNames.insertElementAt("TestRowNames", i);
}
for(int a = 0; a<5; a++){
tableColNames.insertElementAt("TestColNames", a);
}
System.out.println(tableData.toString());
table = new JTable(new SemesterTableModel(tableColNames, tableRowNames, tableData));
table.getColumnModel().getColumn(0).setCellRenderer(new JRowHeader());//Makeshift "rowHeader"
table.setRowHeight(30);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setBackground(Color.LIGHT_GRAY);
JScrollPane scrollPane = new JScrollPane(table);
//scrollPane.setBackground(Color.BLUE);
springLayout.putConstraint(SpringLayout.WEST, scrollPane, 180, SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.NORTH, lblCumGPA, 30, SpringLayout.NORTH, scrollPane);
springLayout.putConstraint(SpringLayout.EAST, comboBoxSemester, -15, SpringLayout.WEST, scrollPane);
springLayout.putConstraint(SpringLayout.EAST, lblCumGPA, -15, SpringLayout.WEST, scrollPane);
springLayout.putConstraint(SpringLayout.EAST, lblSemGPA, -15, SpringLayout.WEST, scrollPane);
springLayout.putConstraint(SpringLayout.SOUTH, btnRemoveSemester, 0, SpringLayout.SOUTH, scrollPane);
springLayout.putConstraint(SpringLayout.EAST, scrollPane, -15, SpringLayout.EAST, this);
springLayout.putConstraint(SpringLayout.NORTH, scrollPane, 15, SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.SOUTH, scrollPane, -15, SpringLayout.SOUTH, this);
add(scrollPane);
table.setFillsViewportHeight(true);
Так вот вы видите, что я инициализировать мой JTable с моим SemesterTableModel и передать мои 3 вектора в качестве параметров для моего SemesterTableModel. Это затем проходит ниже:
public class SemesterTableModel extends AbstractTableModel {
private Vector<String> colNames, rowNames;
private Vector<Vector<String>> data;
public SemesterTableModel() {
colNames = new Vector<String>(1);
rowNames = new Vector<String>(1);
data = new Vector<Vector<String>>(1,1);
}
public SemesterTableModel(Vector<String> colNames, Vector<String> rowNames, Vector<Vector<String>> data){
this.colNames = colNames;
this.rowNames = rowNames;
this.data = data;
}
@Override
public int getColumnCount() {
return colNames.size();
}
@Override
public int getRowCount() {
return rowNames.size();
}
@Override
public Object getValueAt(int col, int row) {
if(col == 0)
return rowNames.elementAt(row);
else if(col >=5 || row >=5) //This is the code I added to figure out where my data was going, before I added this else if statement I was getting the array-index out of bounds errors
return "Out of Bounds";
else
return data.elementAt(row).elementAt(col);
}
@Override
public boolean isCellEditable(int row, int col){
if(col == 0 || row < 5){ //5 is an arbitrary number, I really want this to be an arbitrary variable that will be dependent on another class I haven't finished yet.
return false;
}
return true;
}
}
Так прямо сейчас, когда я запускаю свою программу, моя таблица выглядит следующим образом.
Естественно, я хочу «TestData» падать между ними в «Заголовки строк» и заголовки столбцов, «TestRowNames», чтобы быть в только первый столбец, а затем у меня есть «TestColNames» дон» t даже отображается (хотя, если я правильно помню, мне нужно было бы изменить заголовок столбца через Jtable, а не TableModel).
Очевидно, что я не понимаю что-то здесь, и я некоторое время стучал головой о клавиатуру, пытаясь понять это. Если вы, ребята, знаете, что у вас есть или есть какие-то предложения, я все уши.
Wow ..... Я не могу поверить, что пропустил такую простую ошибку. .. Большое спасибо за то, что поймал это, это работает так же, как и сейчас. Также я ценю предложение для заголовков Row, я обязательно проверю это. – SilverEnsign99