Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Please ask technical questions in the appropriate category. Thank you!

JList where mouse click acts like ctrl-mouse click

843807Mar 13 2010 — edited Apr 7 2010
I'd like to create a JList where I can select multiple items as if the control key were down, but without having the control key down. I thought that perhaps I could do this by extending JList and overriding its processMouseEvent method, setting the MouseEvent object to think that control is pressed and then calling the super method like so, but it doesn't work (I still need to press the control key to get my desired effect):
import java.awt.Component;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;

import javax.swing.*;

public class Ctrl_Down_JList {
  private static void createAndShowUI() {
    String[] items = {"Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"};
    
    JList myJList = new JList(items) {
      @Override
      protected void processMouseEvent(MouseEvent e) {
        
        // change the modifiers to believe that control key is down
        int modifiers = e.getModifiers() | InputEvent.CTRL_DOWN_MASK;
        
        // can I use this anywhere?  I don't see how to change the 
        // modifiersEx of the MouseEvent
        int modifiersEx = e.getModifiersEx() | InputEvent.CTRL_DOWN_MASK;
        
        MouseEvent myME = new MouseEvent(
            (Component) e.getSource(), 
            e.getID(), 
            e.getWhen(), 
            modifiers, // my changed modifier
            e.getX(), 
            e.getY(), 
            e.getXOnScreen(), 
            e.getYOnScreen(), 
            e.getClickCount(), 
            e.isPopupTrigger(), 
            e.getButton());
        super.processMouseEvent(myME);
      }
    };
    
    JFrame frame = new JFrame("Ctrl_Down_JList");
    frame.getContentPane().add(new JScrollPane(myJList));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
        createAndShowUI();
      }
    });
  }
}
Any ideas would be much appreciated!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 5 2010
Added on Mar 13 2010
14 comments
2,449 views