how to select a few continuous columns by pressing mouse and drag in jtable in java

Viewed 34

i can do one column selection by mouse click column header: enter image description here

But what i want is press and drag the mouse to select some continuous columns in jtable, it look likes we do it in excel. I have no idea to make it in jtable, anybody can post some sample code to do it, very thanks in advance ! enter image description here

1 Answers

I don't split hairs,using the "mouse drag" seems difficult to me now, so i use mouse click the aiming column header to select the continuous columns in jtable. Sample code below:

......
public int columnIndex=0 ;  // for save column index
public SumDetail(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
  sumTB.getTableHeader().addMouseListener(getTableHeaderMouseAdapter(sumTB));  
 
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
......
columnIndex=tableModel.getRowCount()-1; 

}
.....
// for clicking on column header to select column
protected MouseAdapter getTableHeaderMouseAdapter(final JTable table) {
return new MouseAdapter() { 
    @Override
    public void mouseClicked(MouseEvent e) {  
         
           int c = table.columnAtPoint(e.getPoint());
           
           if(columnIndex>c){
               table.clearSelection();
              table.setColumnSelectionInterval(c, c);  
           }else{
                 table.setColumnSelectionInterval(columnIndex, c);
           }
                
      
             
          
            if (table.getRowCount() > 0) {
                table.setRowSelectionInterval(0, table.getRowCount() - 1);
                
            }
            
       
            columnIndex=c;
 
            
            if (table.isEditing()) {
                
                table.getCellEditor().stopCellEditing();
                
            }
           
    

    }
};
}

enter image description here

Related