简体   繁体   中英

Having trouble with JTable and JModel

This is my ClanModel class. The table is based on a tree map.

public class ClanModel extends AbstractTableModel{
    private Map<Integer, ClanMember> clanMembers;
    private final String[] columnNames = {"Name", "Rank"};

    ClanModel(Map<Integer, ClanMember> clanMembers){
        this.clanMembers = clanMembers;
    }   

    @Override
    public int getRowCount() {
        return clanMembers.size();
    }

    @Override
    public int getColumnCount() {
        return 2;
    }

    @Override
    public String getColumnName(int column){
        return columnNames[column]; 
    }

    @Override
    public Object getValueAt(int row, int column) {
        if(column == 0) return clanMembers.get(row).getName();
        if(column == 1) return clanMembers.get(row).getRank();
        return 1;
    }

    @Override
    public void setValueAt(Object value, int row, int column) {
        if(column == 0) clanMembers.get(row).setName((String) value);
        if(column == 1) clanMembers.get(row).setRank((Rank) value);
        fireTableCellUpdated(row, column);
    }
}

This is in the gui constructor

clanTable = new JTable(new ClanModel(clanMembers));
panel.add(clanTable);

The map is filled on a button press which is working. However, the table doesn't appear before clicking the button or after. I also get an error every time I resize the gui window.

I have a rough idea of what I need to do to fix it but it hasn't been working out.

Try moving setVisible() so that it's after add() and pack() . See also Initial Threads .

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JTable table = new JTable(new ClanModel(…));
            f.add(new JScrollPane(table));
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM