How to keep a single column from being reordered in a JTable?

前端 未结 8 1810
时光说笑
时光说笑 2020-11-30 09:17

I have a JTable and I need to be able to reorder the columns. However I want the first column to not be able to be re-ordered. I used the following to enable re

8条回答
  •  难免孤独
    2020-11-30 09:28

    This is the solution that I used to prevent the 1st column from being re-ordered

    private int columnValue = -1; 
    private int columnNewValue = -1; 
    
    
    tblResults.getColumnModel().addColumnModelListener(new TableColumnModelListener() 
    { 
        public void columnAdded(TableColumnModelEvent e) {} 
    
        public void columnMarginChanged(ChangeEvent e) {} 
    
        public void columnMoved(TableColumnModelEvent e) 
        { 
            if (columnValue == -1) 
                columnValue = e.getFromIndex(); 
    
            columnNewValue = e.getToIndex(); 
        } 
    
        public void columnRemoved(TableColumnModelEvent e) {} 
    
        public void columnSelectionChanged(ListSelectionEvent e) {} 
    }); 
    
    tblResults.getTableHeader().addMouseListener(new MouseAdapter() 
    { 
        @Override 
        public void mouseReleased(MouseEvent e) 
        { 
            if (columnValue != -1 && (columnValue == 0 || columnNewValue == 0)) 
            tblResults.moveColumn(columnNewValue, columnValue); 
    
            columnValue = -1; 
            columnNewValue = -1; 
        } 
    }); 
    

    Cheers,

提交回复
热议问题