I am writing a hockey pool manager program, and I am having trouble getting a jTable to represent my list of players. What i have are three classes, Team, Roster, and Player. Team has two Roster members, a Bench roster and a Lineup Roster. each roster contains an ArrayList of Players. Players can be added dynamically. I want to have two jTables, one to list players in the Bench Roster, and one for the Lineup Roster. I have made this table model, but i feel i am way off track:
public class PlayerTable extends AbstractTableModel {
private String[] columnNames = {"Name", "Team", "Position", "Injured?", "Salary", "PowerRanking"};
private Roster playerList;
public PlayerTable(Roster players){
playerList = players;
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return playerList.getNumPlayers();
}
public String getColumnName(int col) {
return columnNames[col];
}
public boolean addPlayer(String name, String team, int teamNumber) throws Exception{
return playerList.addPlayer(name, team, teamNumber);
}
public Object getValueAt(int row, int col) {
Object returnValue = "----";
switch (col) {
case 0:
returnValue = playerList.getPlayer(row).getName();
break;
case 1:
returnValue = playerList.getPlayer(row).getTeam();
break;
case 2:
returnValue = playerList.getPlayer(row).getPosition();
break;
case 3:
returnValue = playerList.getPlayer(row).isInjured();
开发者_如何转开发 break;
case 4:
returnValue = playerList.getPlayer(row).getSalary();
break;
case 5:
returnValue = playerList.getPlayer(row).getPawerRanking();
break;
}
return returnValue;
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
}
And I am initializing my jTables with:
jTableBench.setModel(new PlayerTable(userTeam.getBench())
I get an empty Table, but it has the correct column names. now when I go and add a player to the Bench using
userTeam.addPlayerToBench(name, team...)
The table does not change. Am I on the right track here? is this the best way to use a table to represent an set of objects like this? How can i get the table to reflect the changes i have made to the Bench Roster?
The Bean Table Model allows you to display custom Objects easily.
Your table model needs to fire events to inform its view that the model has changed. In your case, you should use fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1)
. Look at the javadoc of AbstractTableModel
to discover which events may be fired.
You should thus use the model to add a player. The model will add a player to the playerList it holds, and would also fire the appropriate event.
精彩评论