Search code examples
javajtablelistenerkeylistenerlistselectionlistener

How to select the cell on mouse click and shift in JGrid similar to (JTable)?


I have the ListSelectionListener which tells me when the cell is selected with the mouse.

JGrid grid = new JGrid();
grid.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
grid.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

   @Override
   public void valueChanged(final ListSelectionEvent e) {
       e.getFirstIndex();
       e.getLastIndex()
   }
}

I want to select the sell only when the button shift is hold. How can i do it?

I need it for the multiple selection. When the user holds shift and clicks the cells it gives me getFirstIndex() and getLastIndex().


Solution

  • Add a KeyListener similar to this to your JGrid, assuming JGrids takes keyListeners

    boolean shiftIsDown = false;
    
    yourJGrid.addKeyListener(new KeyListener()
            {
                public void keyPressed(KeyEvent e)
                {
                    if (e.getKeyCode == e.VK_SHIFT) shiftIsDown = true; 
                }
    
                public void keyReleased(KeyEvent e)
                {
                     if (e.getKeyCode == e.VK_SHIFT && 
                         shiftIsDown == true) shiftIsDown = false;
                }
    
                public void keyTyped(KeyEvent e)
                {
                    // nothing
                }
    
            });
    

    Now when you get a valueChanged() event, just check to see if your boolean "shiftIsDown" value is true, and if so you can do your selection.