How to detect SHIFT key in action events


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: How to detect SHIFT key in action events

  1. #1
    Minh Guest

    How to detect SHIFT key in action events


    I want to detect whether the SHIFT key is held down when a button is pressed.
    Here is what I am doing:

    JButton butt = new JButton("Click me!");

    butt.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
    if ( (e.getModifiers() & ActionEvent.SHIFT_MASK) != 0)
    JOptionPane.showMessageDialog(null, "SHIFT key is pressed.");
    else
    JOptionPane.showMessageDialog(null, "SHIFT key is not pressed.");
    }
    });

    While testing this code, what I find out is that e.getModifiers() always
    returns 0 and hence the message "SHIFT key is not pressed." is always displayed.

    How do I enable the tracking of keys such as SHIFT, CNTRL or ALT ?

    Any help is appreciated.
    Minh.


  2. #2
    Anon Guest

    Re: How to detect SHIFT key in action events


    Key events arnt distributed toward the action listeners, have to use and declare
    KeyListener separate and just register with a bool in same class that shift
    has been pressed and released.

    Anon

    "Minh" <java.@127.0.0.1> wrote:
    >
    >I want to detect whether the SHIFT key is held down when a button is pressed.
    > Here is what I am doing:
    >
    >JButton butt = new JButton("Click me!");
    >
    >butt.addActionListener(new ActionListener() {
    > public void actionPerformed(ActionEvent e)
    > {
    > if ( (e.getModifiers() & ActionEvent.SHIFT_MASK) != 0)
    > JOptionPane.showMessageDialog(null, "SHIFT key is pressed.");
    > else
    > JOptionPane.showMessageDialog(null, "SHIFT key is not pressed.");
    > }
    >});
    >
    >While testing this code, what I find out is that e.getModifiers() always
    >returns 0 and hence the message "SHIFT key is not pressed." is always displayed.
    >
    >How do I enable the tracking of keys such as SHIFT, CNTRL or ALT ?
    >
    >Any help is appreciated.
    >Minh.
    >



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center