KeyEvent Handling

Hello everyone.
I'm using Netbeans 5.0 to build a form project. I have a class that extends from JFrame and I wanted to make it a KeyListener. So I set on the design window the desired events I wanted my frame to handle, which were keyPressed, keyReleased and keyTyped. Netbeans has generated the following code:
addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            public void keyReleased(java.awt.event.KeyEvent evt) {
                formKeyReleased(evt);
            public void keyTyped(java.awt.event.KeyEvent evt) {
                formKeyTyped(evt);
        });and also generated the methods formKey<action> stated above. I wrote the methods and they work ok. But when I ran the project the key listening didn't work properly. Using Netbeans debugger, I found out that the following happens: in the code above, when the first method is called (formKeyPressed), the object evt is correctly set, with a valid key code. The program goes on because the key that I pressed is suposed to be treated in formKeyTyped. When formKeyTyped is invoked, however, object evt has its code set to 0, although its char is unchanged. Does anyone knows why it happens?

and the key handling code is built as follows
switch (evt.getKeyCode()){
              case KeyEvent.VK_MINUS:
               //code
               break;
              case KeyEvent.VK_UNDERSCORE:
               //code
               break;
}in all three methods

Similar Messages

  • Currency Format

    Good evening everyone,
    I am working on a banking system and I have a field that needs to be automatically updated with a certain format (i,e: format the currency on-the-fly). I have used two options
    1 - Used a method that returns Document object and validate the field.
    2 - Used the KeyEvent handler (keyReleased()).
    The question is:
    is there a ready class or method for such thing, since I am left with little changes.
    If I continue with my approaches what is the best way?
    thanx in advance

    Java_Madness wrote:
    Good evening everyone,
    I am working on a banking system and I have a field that needs to be automatically updated with a certain format (i,e: format the currency on-the-fly). I have used two options
    1 - Used a method that returns Document object and validate the field.
    2 - Used the KeyEvent handler (keyReleased()).
    The question is:
    is there a ready class or method for such thing, since I am left with little changes.
    If I continue with my approaches what is the best way?A JFormattedTextField with an InputVerifier may be what you want.
    Jim S.

  • Multiple KeyEvents?

    Hello,
    i have a problem with KeyEvent handling. I've wrote an own behavior class which changes the camera positon of the view vertical in a 45� degree limit. All works fine.
    Now it is usefull to change the key Event to specific keys like up and down. After several tries i've noticed that only the KeyEvent.KeyPressed ID and the other global KeyEvents work, the VK specific keyevent not..
    Why? Can someone help?
    Thx in advance,
    Christian

    insert that just after your process stimulus called e
    WakeupOnAWTEvent ev;
    WakeupCriterion genericEvt;
    genericEvt = (WakeupCriterion) e.nextElement();
              ev = (WakeupOnAWTEvent) genericEvt;
              AWTEvent[] events;
              events = ev.getAWTEvent();
              KeyEvent eve = (KeyEvent)events[0];
              if (eve.getKeyCode()==KeyEvent.VK_RIGHT)
                   //do your action               
              }

  • Interval race condition - AS3 bug??

    I have included the output and the two code segments that
    trigger the output. I do not understand how this could happen.
    Trace shows that clearInterval(19) occurs yet Wakeup seems to
    trigger spontaneously still trying to clearInterval(19). This
    occurs when user strums keypad triggering multiple calls to
    KeyDownFunc. You can execute this code yourself by selecting
    Lesson1 on page 1 of ItOnlyTakes1.org. It takes a few strumming
    tries to trigger it but the following code demonstrates what is
    happening within. Need help. (Interesting to note that 16 was never
    cleared.)
    Following code triggers the generation of a new display which
    requires a user answer to be caught in KeyDownFunc. sleepID is a
    global variable.
    private function WakeUp():void {
    clearInterval(sleepID);
    trace("Wakeup calling: Cleared " + sleepID);
    NewNumber();
    Internal part of KeyDownFunc that calls WakeUp to trigger new
    problem. The sleep interval is the time needed for the user to view
    the correct answer was given BEFORE triggering a new WakeUP and
    thus a new number
    if (answer.length == subquanAnswer.length) {
    if (answer == subquanAnswer && answerSign ==
    subquanAnswerSign ) {
    soundOutChannel = answerSound.play();
    sleepID = setInterval(WakeUp, 1000);
    trace("Call Wakeup: answer is " + answer + " " +
    subquanAnswer + " New sleepID: " + sleepID);
    gradeText.text=" CORRECT";
    gradeText.setTextFormat(correctanswerformat);
    } else {
    gradeText.text=" INCORRECT";
    gradeText.setTextFormat(incorrectanswerformat);
    Output showing problem:
    introListener calling
    Call Wakeup: answer is 7 7 New sleepID: 2
    Wakeup calling: Cleared 2
    Call Wakeup: answer is 7 7 New sleepID: 4
    Wakeup calling: Cleared 4
    Call Wakeup: answer is 7 7 New sleepID: 6
    Wakeup calling: Cleared 6
    Call Wakeup: answer is 4 4 New sleepID: 8
    Wakeup calling: Cleared 8
    Call Wakeup: answer is 4 4 New sleepID: 10
    Wakeup calling: Cleared 10
    Call Wakeup: answer is 9 9 New sleepID: 12
    Wakeup calling: Cleared 12
    Call Wakeup: answer is 9 9 New sleepID: 14
    Wakeup calling: Cleared 14
    Call Wakeup: answer is 4 4 New sleepID: 16
    Call Wakeup: answer is 4 4 New sleepID: 17
    Wakeup calling: Cleared 17
    Call Wakeup: answer is 6 6 New sleepID: 19
    Wakeup calling: Cleared 19
    Wakeup calling: Cleared 19
    Wakeup calling: Cleared 19
    Wakeup calling: Cleared 19
    Wakeup calling: Cleared 19
    Wakeup calling: Cleared 19
    Wakeup calling: Cleared 19
    Wakeup calling: Cleared 19

    To all,
    I understand the insistence to clear before setting, but I
    have not figured out how to get clearing and setting into the same
    function. I am currently using a flag to avoid the race condition
    that my code, not AS3, has created. This is what I am rethinking.
    My current flow is like this.
    1) generate a NewNumber()
    2) check keys until correct number entered using KeyEvent.
    Then set an interval to wait until the student has had time to
    consider the correctness of this answer and to play the audio
    feedback.
    3) Interval timeout triggers WakeUp which clears the interval
    then generates a NewNumber.
    Only problem was, kids kept entering keys AFTER they had
    answered correctly which, before my using a flag, was triggering
    new setIntervals and the problem above.
    I do not see how I can have my KeyEvent handler clear the
    interval or how I can have my WakeUp functions set the interval.
    They are two distinct functions.
    If I do not clear the interval in WakeUp a long delay in
    answering will trigger another NewNumber.
    If I set it in WakeUp then I don't give the student enough
    time to answer.
    If I do not set it in keydown then I don't know how to ensure
    they have time to see and hear the feedback
    I can't clear it in KeyDownFunc because the kid may not push
    a key and allow WakeUP to create a NewNumber()
    I hope my brain isn't frying.
    I do appreciate the continued effort in helping me and help
    on this forum has improved my coding almost as much as if I had
    someone watching over my shoulder. LOL, that would be
    instantaneous.

  • [help] - Flash animation for i-mode mobile

    Hi! ^^
    I'm getting a trouble while creating a game for i-mode
    mobiles (DoCoMo)
    It works fine in Flash8 mobile simulator. But when I tested
    it in i-mode Simulator II, I got a (big) trouble:
    The animations perform not very slowly but when I hold down a
    key to move the character in the game, every animations are nearly
    stopped! only the character can move, and when it moves, all
    animations inside it are stopped too :(
    Everythings can only move again when I release the key :)
    Can anyone tell me how to solve this problem?
    ah, moreover, even when I hold down a key but let the
    flashplayer do nothing (i don't make the character move anymore and
    let all the movieclips work it own), the animations still slow
    down. It seem that the CPU spend too much time/power to process
    these keyevents :(
    Thanks ^o^

    yeah sure, it works fine :) That's also the way I solved my
    problem. Thanks again ^^
    But I think this could be very complex in some kind of games.
    For example: a game that has a moving background (controled by AS,
    not just a simple animation), and while the background is moving,
    we need to make the characters move by pressing some keys.
    In this case, when the key is pressed, I need to make all the
    objects move: background, characters,... So a piece of code must be
    placed in the keyevent handler's functions to control the moving of
    the backgorund. But it only be excuted when keypressed. So to make
    the background moves all the time, another copy of that code must
    be placed somewhere else.
    -> There's some duplicated codes (do exactly the same
    work) excuted at the same time and they may cause some problem...
    It's just how I solved my problem +_+
    Maybe you have a greater idea ^^
    Thanks for reading! (my English is not good, heh)

  • Handling KeyEvent (filtering KeyEvents)

    I am writing a code to learn how KeyEvents behaves and how to manipulate and even filtering some events, for example, to filter the normal behaviour of keeping pressed a key that fires a KeyPressed -> KeyTyped -> KeyReleased Events, like pressing the 'a' button, and keeping it pressed, this fires the sequence expressed before as long as the button is keeped pressed.
    From the writing a KeyListener tutorial, (http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html), i've begin to make some tests and changing somethings around the code, but, i am not getting too far as I want to make the 'keeping pressed' behaviour as just one event, the KeyPressed, and only when the user release the key, the KeyReleased Event should be fired.
    In resume, i just want to make any keystroke to be mapped as a modifier key, such as Shift or Control, because i will need a program which only responds with a character to the user, when he releases the key and not just like the KeyTyped Event.
    I am not a programmer, i am just a psychology student who wants to learn about Java programming language and try to apply it to some ideas about how to gather information about the behaviour of people when it's method of interact (virtually) is the keyboard realm.
    Is there anything out there to help me on this trail of learning how to manipulate KeyEvents?
    Thanks in advance, and sorry for the poor english.

    Hi,
    This is a bit of a hack but works nicely. Substitute the keyPressed, KeyReleased and keyTyped methods with the following:
        /** Handle the key typed event from the text field. */
        public void keyTyped(KeyEvent e) {
        //    displayInfo(e, "KEY TYPED: ");
        /** Handle the key pressed event from the text field. */
        public void keyPressed(KeyEvent e) {
            if(key != e.getKeyChar()) {
                displayInfo(e, "KEY PRESSED: ");
                key = e.getKeyChar();
        /** Handle the key released event from the text field. */
        public void keyReleased(KeyEvent e) {
            displayInfo(e, "KEY RELEASED: ");
            key = ' ';
        }and declare a char as a class varible like this:
    // ... import statements here
    public class KeyEventDemo extends JPanel
                              implements KeyListener,
                                         ActionListener {
        JTextArea displayArea;
        JTextField typingArea;
        static final String newline = "\n";
        // This is where you'll put the char.
        char key;
        public KeyEventDemo() {
            super(new BorderLayout());
            // ... the rest of the class

  • Handling KeyEvent in a JFrame

    i have a JFrame with several JTextFields. i want the JFrame to register the enter key whent it is pressed in any of those textFields. basically, i want the JFrame to react to "enter" keyEvent as if the "ok" button is pressed.
    how do i do that?

    You don't need the additional overhead of a key listener just for the <enter> key
    myTextField.addActionListener(this)

  • Keyevent used for setMnemonic show in editable jtextarea

    I don't know if this has been fix. I notice that if I used the setMnemonic to access a editable jtextarea, that the key I used is inserted into the jtextarea. After searching the web, I found nothing about this problem.
    So, I took the program from the java tutorial, MenuDemo.java and reproduct the same problem but setting the jtextarea to editable (output.setEditable(true). It happens everytime. Below is the MenuDemo.java with the change. By selecting t or b in the A Menu menu,then which ever t or b used will show up in the text area after the expected line displays. I am using 1.5 so this problem may have been fix.
    If anyone knows if it has or a work around, please let me know.
    Thanks
    Kevin
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.ButtonGroup;
    import javax.swing.JMenuBar;
    import javax.swing.KeyStroke;
    import javax.swing.ImageIcon;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    * This class adds event handling to MenuLookDemo.
    public class MenuDemo extends JFrame
    implements ActionListener, ItemListener {
    JTextArea output;
    JScrollPane scrollPane;
    String newline = "\n";
    public MenuDemo() {
    JMenuBar menuBar;
    JMenu menu, submenu;
    JMenuItem menuItem;
    JRadioButtonMenuItem rbMenuItem;
    JCheckBoxMenuItem cbMenuItem;
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    //Add regular components to the window, using the default BorderLayout.
    Container contentPane = getContentPane();
    output = new JTextArea(5, 30);
    output.setEditable(true);
    scrollPane = new JScrollPane(output);
    contentPane.add(scrollPane, BorderLayout.CENTER);
    //Create the menu bar.
    menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    //Build the first menu.
    menu = new JMenu("A Menu");
    menu.setMnemonic(KeyEvent.VK_A);
    menu.getAccessibleContext().setAccessibleDescription(
    "The only menu in this program that has menu items");
    menuBar.add(menu);
    //a group of JMenuItems
    menuItem = new JMenuItem("A text-only menu item",
    KeyEvent.VK_T);
    //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_1, ActionEvent.ALT_MASK));
    menuItem.getAccessibleContext().setAccessibleDescription(
    "This doesn't really do anything");
    menuItem.addActionListener(this);
    menu.add(menuItem);
    menuItem = new JMenuItem("Both text and icon",
    new ImageIcon("images/middle.gif"));
    menuItem.setMnemonic(KeyEvent.VK_B);
    menuItem.addActionListener(this);
    menu.add(menuItem);
    menuItem = new JMenuItem(new ImageIcon("images/middle.gif"));
    menuItem.setMnemonic(KeyEvent.VK_D);
    menuItem.addActionListener(this);
    menu.add(menuItem);
    //a group of radio button menu items
    menu.addSeparator();
    ButtonGroup group = new ButtonGroup();
    rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
    rbMenuItem.setSelected(true);
    rbMenuItem.setMnemonic(KeyEvent.VK_R);
    group.add(rbMenuItem);
    rbMenuItem.addActionListener(this);
    menu.add(rbMenuItem);
    rbMenuItem = new JRadioButtonMenuItem("Another one");
    rbMenuItem.setMnemonic(KeyEvent.VK_O);
    group.add(rbMenuItem);
    rbMenuItem.addActionListener(this);
    menu.add(rbMenuItem);
    //a group of check box menu items
    menu.addSeparator();
    cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
    cbMenuItem.setMnemonic(KeyEvent.VK_C);
    cbMenuItem.addItemListener(this);
    menu.add(cbMenuItem);
    cbMenuItem = new JCheckBoxMenuItem("Another one");
    cbMenuItem.setMnemonic(KeyEvent.VK_H);
    cbMenuItem.addItemListener(this);
    menu.add(cbMenuItem);
    //a submenu
    menu.addSeparator();
    submenu = new JMenu("A submenu");
    submenu.setMnemonic(KeyEvent.VK_S);
    menuItem = new JMenuItem("An item in the submenu");
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_2, ActionEvent.ALT_MASK));
    menuItem.addActionListener(this);
    submenu.add(menuItem);
    menuItem = new JMenuItem("Another item");
    menuItem.addActionListener(this);
    submenu.add(menuItem);
    menu.add(submenu);
    //Build second menu in the menu bar.
    menu = new JMenu("Another Menu");
    menu.setMnemonic(KeyEvent.VK_N);
    menu.getAccessibleContext().setAccessibleDescription(
    "This menu does nothing");
    menuBar.add(menu);
    public void actionPerformed(ActionEvent e) {
    JMenuItem source = (JMenuItem)(e.getSource());
    String s = "Action event detected."
    + newline
    + " Event source: " + source.getText()
    + " (an instance of " + getClassName(source) + ")";
    output.append(s + newline);
    public void itemStateChanged(ItemEvent e) {
    JMenuItem source = (JMenuItem)(e.getSource());
    String s = "Item event detected."
    + newline
    + " Event source: " + source.getText()
    + " (an instance of " + getClassName(source) + ")"
    + newline
    + " New state: "
    + ((e.getStateChange() == ItemEvent.SELECTED) ?
    "selected":"unselected");
    output.append(s + newline);
    // Returns just the class name -- no package info.
    protected String getClassName(Object o) {
    String classString = o.getClass().getName();
    int dotIndex = classString.lastIndexOf(".");
    return classString.substring(dotIndex+1);
    public static void main(String[] args) {
    MenuDemo window = new MenuDemo();
    window.setTitle("MenuDemo");
    window.setSize(450, 260);
    window.setVisible(true);

    Yes your are correct. I forgot why I went to 1.5 but until better time come along and I can get a new computer, I will have to live with 1.4.2._06. But, it did fit my problem.

  • JTextField keyEvent consume()

    This question is related to the keyEvent-architecture.
    The JTextField (or any JTextComponent for that matter) is designed to use the keyEvents but NOT consume it. Which means the JTextField modifies its internal Document-model and leaves the keyEvent to propagate further for any body (parent-component etc.) to use it.
    I dont really understand why the design leaves that event to be used by anybody with key-mapping for that keyEvent !?!
    In the specific problem that I have, I am putting JTextField in MainFrame which also has zoomIn/zoomOut Menu-actions attached to Minus(-) and Plus(+) keys respectively.
    What I notice is whenever I type, Minus(-) in JTextField, zoomIn is invoked !!
    Well, I was able to prevent that from happening by attaching a keyListener to my JTextField whose ONLY JOB is to consume() ALL keyevents. (ConsumeAllKeysListener)
    This preety much solves my problem. But I would like to know, is this the correct way to prevent STRAY keyEvent propagation ?
    Also until now, I thought that the JTextField uses InputMap/ActionMap to append all the regular keys that are typed. This assumption is does not seem to be true since even when I consume all the keyEvents by attaching the "ConsumeAllKeysListener" the keys actually end up being typed in the JTextField (although that is what I want).
    But, this behaviour makes me think that JTextField has its Document/model setup as keyListener to itself rather that handling the keyEvent using InputMap/ActionMap. Is this true ?
    Hope I am not confusing the matter !?!
    Thanks in anticipation,
    -sharad

    As mentioned above the correct way to do this is to use a Document to edit any characters as they are typed. The reason for this is that this approach will work whether data is 'typed' or 'pasted' into the text field. Check out this section from the Swing tutorial for more information on Documents and examples:
    http://java.sun.com/docs/books/tutorial/uiswing/components/textfield.html#validation
    I do not recommend using a KeyListener, but here is the reason why it doesn't work.
    Three events are generated every time you type a character into a text field:
    1) key pressed
    2) key typed
    3) key released
    The key typed event seems to be the important event for adding text to the text field so you could add code in the keyTyped(..) method:
    if (e.getKeyChar() == ',')
        e.consume();

  • How to add event handling for a menu?

    hi,
    I have created a menu and few mneu items.
    for eachmenu itme , i did event handling and it is workign fine.
    it was like this
    menuItem = new JMenuItem("Exit",KeyEvent.VK_X);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK));
    menuItem.addActionListener(this);
    menu.add(menuItem);
         public void actionPerformed(ActionEvent e)
    JMenuItem source = (JMenuItem)(e.getSource());
    String s = "Action event detected. Event source: " + source.getText();
    System.out.println(s);     
    public void itemStateChanged(ItemEvent e)
    JMenuItem source = (JMenuItem)(e.getSource());
    String s = "Item event detected. Event source: " + source.getText();
    System.out.println(s);
    now int he second menu i don't have any menu item and i want to do the event handling for the menu itself. any ideas how to do it. following is the code for the menu
    //Build the second menu.
    menu2 = new JMenu("Options");
    menu2.setMnemonic(KeyEvent.VK_O);
    menuBar.add(menu2);
    menu2.addActionListener(this);     //this does nto work

    You were on the right track. However, selecting a menu is different from selecting a menu item. MenuItem chucks an ActionEvent and Menu will send an ItemEvent.
    If you pile all action output to one actionPerformed method then be careful of your assumptions on what the source type will be. If by any chance the Menu has sent an ActinoEvent then your code will have caused a ClassCastException.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MenuTest implements ActionListener, ItemListener {
        JMenuItem menuItem;
        JMenu menu1, menu2;
        JMenuBar menubar;
        JFrame frame;
        public MenuTest() {
            frame = new JFrame("MenuTest");
            frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
            menubar = new JMenuBar();
            frame.setJMenuBar(menubar);
            menu1 = new JMenu("File");
            menu1.setMnemonic(KeyEvent.VK_F);
            menuItem = new JMenuItem("Exit",KeyEvent.VK_X);
            menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK));
            menuItem.addActionListener(this);
            menu1.addItemListener(this);
            menu1.add(menuItem);
            menubar.add(menu1);
            //Build the second menu.
            menu2 = new JMenu("Options");
            menu2.setMnemonic(KeyEvent.VK_O);
            menu2.addActionListener(this); //this does not work
            menu2.addItemListener(this); // use this instead
            menubar.add(menu2);
            JPanel panel = new JPanel();
            panel.setPreferredSize(new Dimension(100,100));
            frame.getContentPane().add(panel);
            frame.pack();
            frame.show();
        public void actionPerformed(ActionEvent e)
            String s = "Action event detected. Event source: " + e.getSource();
            System.out.println(s);
        public void itemStateChanged(ItemEvent e)
            String s = "Item event detected. Event source: " + e.getSource();
            System.out.println(s);
        public static void main(String[] args) {
            new MenuTest();
    }

  • Making a cutsom event handler for nodes

    hi i was wondering how to go about making a custom eventhandler class for nodes
    for eg. if a have a circle (c1) in the main.fx file
    and i want to assign it Mouse and Key events(using onMousePressed etc)
    but i dont want to write it in "c1"'s definiton directly coz i want the event handling code to be useful for another circle i may create later(call it c2)
    can some tell me how to go about it ?
    Appreciated. :-)
    UPDATE:
    ok i just realized that i could simply write a modified Circle class extending the Circle class.
    So i can just create a new modified Circle object when needed.But how do i exactly write the class.The fixed variables i can simply override.But what about the event handling properties of the circle,how do i make sure they are initialzed for that object when the modified Circle object is created? what is the syntax??
    Edited by: apratim_pranay on Apr 22, 2010 6:16 AM

    hey i tried making a circle class like the above..
    drag works fine..
    thing is.. i've nested some effects..which "SHOULD" toggle on on keypresses ,but even though the key press is detected..effects dont appear..
    public class modCircle extends Circle{
    var c1e2:Glow;
    var c1e4:Reflection=Reflection {bottomOpacity:0.0 topOpacity:0.5
                                 fraction: 0.75 topOffset: 0.0};
         override var centerX=40;
         override var centerY=199;
         override var radius=40 ;
         override var fill= Color.BLACK;
         override var effect=c1e2=Glow {level:0.1 input:c1e4};
    override def onMouseEntered= function( e: MouseEvent )
                              {requestFocus();}
    override def onKeyPressed= function (e: KeyEvent): Void
                               if(e.code==KeyCode.VK_G)
                                   if(c1e2.level==0.1)
                                    {c1e2.level=0.9}
                                   else
                                    {c1e2.level=0.1}
                                 if(e.code==KeyCode.VK_M)
                                   if(c1e4.topOpacity==0.5)
                                     c1e4.fraction= 0.75;c1e4.topOffset= 0.0;
                                     c1e4.topOpacity= 0.5;c1e4.bottomOpacity= 0.0;
                                   else
                                     c1e4.fraction= 0.75;c1e4.topOffset= 0.0;
                                     c1e4.topOpacity= 0.5;c1e4.bottomOpacity= 0.0;
    }why is this happening??

  • Key Handler

    //My source code:
    package keyhandler;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.util.Collections;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Set;
    import javax.swing.JFrame;
    public class Handler implements KeyListener {
    private boolean FINISH = true;
    private Set<Integer> set;
    *@param args*
    public Handler() {
    set = Collections.synchronizedSet(new HashSet<Integer>());
    public void handle() {
    while (FINISH) {
    synchronized (set) {
    Iterator<Integer> i = set.iterator();
    String k= "";
    while (i.hasNext()) {
    int key = i.next();
    switch (key) {
    case 27: FINISH=false;break;
    case 38:k = k.concat(" Up");break;
    case 39:k = k.concat(" right");break;
    case 40:k = k.concat(" down");break;
    case 37:k = k.concat(" left");break;
    default :k = k.concat(" "+key);break;
    System.out.println(k);
    System.exit(0);
    public static void main(String[] args) {
    Handler handler = new Handler();
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.addKeyListener(handler);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    handler.handle();
    @Override
    public void keyPressed(KeyEvent arg0) {
    synchronized (set) {
    set.add(arg0.getKeyCode());
    @Override
    public void keyReleased(KeyEvent arg0) {
    synchronized (set) {
    set.remove(arg0.getKeyCode());
    @Override
    public void keyTyped(KeyEvent arg0) {
    // TODO Auto-generated method stub
    // I 've got this code to handle keys. I am making an interface for a game and I would like to handle more than one key at same time. I want to handle the arrow keys. It seems to be fine except when I am holding down the Up arrow key i can hold just another key at same time.
    Example :
    Down Left Right - holding down left and right arrow key at same time
    Up left - with up arrow key i can hold just another one key. Not more.
    Can anybody help me to sort out this source?

    Thanks for your idea, very cool very useful
    [fresh fridays |http://reggae-cd.net/fresh-fridays-reggae-dance-in-jamaica]
    [passa passa DVD |http://reggae-dvd.com/passa-passa-reggae-music-and-dancing]
    [passa passa  |http://bestreggaemusic.com/passa-passa-90-mavado-fall-rain-fall-official-dance]
    [reggae videos|http://reggae-dancehall.net/crabb-up-friday-dancehall-reggae]

  • KeyEvent consume

    Hi!,
    It's me again, he9x, ahm having progress with my testlayout/calculator...just having problems with the KeyEvent consume method. I'm trying to limit the entry of DOT ex. 3.23 - allowed
    .45 - allowed
    .46.67 or 4.566.67 - not allowed
    Here's my code that handles it, but the problem is when I try to enter 4.56. upon entering the second period my message pops up and the second period is displayed. even though it pass through the event.consume method. should it not display the period? Thank you so much for your help!
    here's my code
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TestLayout extends JFrame{
        //private JTextField text;   
        private IntegerTextField text;
        private JButton btnOne, btnTwo, btnThree, btnFour, btnFive,
                        btnSix, btnSeven, btnEight, btnNine, btnZero,
                        btnAdd, btnSubtract, btnMultiply, btnDivide,
                        btnSqrRt, btnModulo, btnBack, btnCE;
        private JPanel northPanel, centerPanel, southPanel;
        private int textNum;
        public TestLayout(){
           Container container = getContentPane();
           //text = new JTextField(14);
           //text = new TestLayout().new IntegerTextField(14);
           text = new IntegerTextField(14);
           text.setPreferredSize(new Dimension(255, 20));
           text.setHorizontalAlignment(JTextField.TRAILING);
           text.addActionListener(new ActionHandler());
           northPanel = new JPanel();
           northPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
           northPanel.add(text);
           container.add(northPanel, BorderLayout.NORTH);
           centerPanel = new JPanel();
           centerPanel.setLayout(new GridLayout(4, 4));
           btnOne = new JButton("1");
           btnTwo = new JButton("2");
           btnThree = new JButton("3");
           btnFour = new JButton("4");
           btnFive = new JButton("5");
           btnSix = new JButton("6");
           btnSeven = new JButton("7");
           btnEight = new JButton("8");
           btnNine = new JButton("9");
           btnZero = new JButton("0");
           btnMultiply = new JButton("*");
           btnDivide = new JButton("/");
           btnAdd = new JButton("+");
           btnSubtract = new JButton("-");
           btnSqrRt = new JButton("sqrt");
           btnModulo = new JButton("%");
           centerPanel.add(btnOne);
           centerPanel.add(btnTwo);
           centerPanel.add(btnThree);
           centerPanel.add(btnFour);      
           centerPanel.add(btnFive);
           centerPanel.add(btnSix);
           centerPanel.add(btnSeven);
           centerPanel.add(btnEight);      
           centerPanel.add(btnNine);
           centerPanel.add(btnZero);
           centerPanel.add(btnMultiply);
           centerPanel.add(btnDivide);      
           centerPanel.add(btnAdd);
           centerPanel.add(btnSubtract);
           centerPanel.add(btnSqrRt);
           centerPanel.add(btnModulo);      
           container.add(centerPanel, BorderLayout.CENTER);
           southPanel = new JPanel();
           southPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
           btnBack = new JButton("Backspace");
           btnCE   = new JButton("   CE    ");
           southPanel.add(btnBack);
           southPanel.add(btnCE);
           container.add(southPanel, BorderLayout.SOUTH);
           setSize(275, 250);
           setVisible(true);
        private class ActionHandler implements ActionListener {
           public void actionPerformed(ActionEvent event){
               if(event.getSource() == text)
                  computeText();
        private void computeText(){
           int num = Integer.parseInt(text.getText()) -1;
           text.setText(String.valueOf(num));
        private class IntegerTextField extends JTextField{
           //final static String badchars = "`~!@#$%^&*()_+=\\|\"':;?/>.<, ";
           final static String badchars = "`~!@#$%^&*()_+=\\|\"':;?/><, ";
           public IntegerTextField(int columns){
                  super(columns);
           public void processKeyEvent(KeyEvent event){
                  char c = event.getKeyChar();
                if ( (Character.isLetter(c) && !event.isAltDown())
                     || badchars.indexOf(c) > -1) {
                     event.consume();
                     return;
                if ( (c == '-') && getDocument().getLength() > 0 ){
                     event.consume();}
                else{
                     super.processKeyEvent(event);
                if ( (c == '.') && (getText().lastIndexOf(c) != getText().indexOf(c)) ){
                     event.consume();
                     String temp = String.valueOf(c) + String.valueOf(getText().lastIndexOf(c));
                     if (event.isConsumed()) JOptionPane.showMessageDialog(null, temp);
                }else{
                     super.processKeyEvent(event);
        public static void main(String args[]){
           TestLayout test = new TestLayout();
           //test = new TestLayout();
           test.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    Hi!
    Thanks for that Sir! heres my new code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TestLayout extends JFrame{
        //private JTextField text;   
        private IntegerTextField text;
        private JButton btnOne, btnTwo, btnThree, btnFour, btnFive,
                        btnSix, btnSeven, btnEight, btnNine, btnZero,
                        btnAdd, btnSubtract, btnMultiply, btnDivide,
                        btnSqrRt, btnModulo, btnBack, btnCE;
        private JPanel northPanel, centerPanel, southPanel;
        private int textNum;
        public TestLayout(){
           Container container = getContentPane();
           //text = new JTextField(14);
           //text = new TestLayout().new IntegerTextField(14);
           text = new IntegerTextField(14);
           text.setPreferredSize(new Dimension(255, 20));
           text.setHorizontalAlignment(JTextField.TRAILING);
           text.addActionListener(new ActionHandler());
           northPanel = new JPanel();
           northPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
           northPanel.add(text);
           container.add(northPanel, BorderLayout.NORTH);
           centerPanel = new JPanel();
           centerPanel.setLayout(new GridLayout(4, 4));
           btnOne = new JButton("1");
           btnTwo = new JButton("2");
           btnThree = new JButton("3");
           btnFour = new JButton("4");
           btnFive = new JButton("5");
           btnSix = new JButton("6");
           btnSeven = new JButton("7");
           btnEight = new JButton("8");
           btnNine = new JButton("9");
           btnZero = new JButton("0");
           btnMultiply = new JButton("*");
           btnDivide = new JButton("/");
           btnAdd = new JButton("+");
           btnSubtract = new JButton("-");
           btnSqrRt = new JButton("sqrt");
           btnModulo = new JButton("%");
           centerPanel.add(btnOne);
           centerPanel.add(btnTwo);
           centerPanel.add(btnThree);
           centerPanel.add(btnFour);      
           centerPanel.add(btnFive);
           centerPanel.add(btnSix);
           centerPanel.add(btnSeven);
           centerPanel.add(btnEight);      
           centerPanel.add(btnNine);
           centerPanel.add(btnZero);
           centerPanel.add(btnMultiply);
           centerPanel.add(btnDivide);      
           centerPanel.add(btnAdd);
           centerPanel.add(btnSubtract);
           centerPanel.add(btnSqrRt);
           centerPanel.add(btnModulo);      
           container.add(centerPanel, BorderLayout.CENTER);
           southPanel = new JPanel();
           southPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
           btnBack = new JButton("Backspace");
           btnCE   = new JButton("   CE    ");
           southPanel.add(btnBack);
           southPanel.add(btnCE);
           container.add(southPanel, BorderLayout.SOUTH);
           setSize(275, 250);
           setVisible(true);
        private class ActionHandler implements ActionListener {
           public void actionPerformed(ActionEvent event){
               if(event.getSource() == text)
                  computeText();
        private void computeText(){
           int num = Integer.parseInt(text.getText()) -1;
           text.setText(String.valueOf(num));
        private class IntegerTextField extends JTextField{
           //final static String badchars = "`~!@#$%^&*()_+=\\|\"':;?/>.<, ";
           final static String badchars = "`~!@#$%^&*()_+=\\|\"':;?/><, ";
           public IntegerTextField(int columns){
                  super(columns);
           public void processKeyEvent(KeyEvent event){
                  char c = event.getKeyChar();
                if ( (Character.isLetter(c) && !event.isAltDown())
                     || badchars.indexOf(c) > -1) {
                     event.consume();
                     return;
                if ( (c == '-') && getDocument().getLength() > 0 )
                     event.consume();
                else if( (c == '.') && getText().indexOf(c) > -1 )
                     event.consume();
                else
                     super.processKeyEvent(event);
        public static void main(String args[]){
           TestLayout test = new TestLayout();
           //test = new TestLayout();
           test.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

  • "Tab" KeyEvent ignored

    Hi!
    I have a simple scene with a BorderPane and an attached onKeyPressed-Action called "actionXYZ".
    <BorderPane onKeyPressed="#actionXYZ" xmlns:fx="http://javafx.com/fxml">
    </BorderPane> The method "actionXYZ" should do something, whenever I press the TAB-Key (KeyCode.TAB).
    public static void actionXYZ(KeyEvent event) {
       if (event.getCode() == KeyCode.TAB) {
              // done something
    } Problem now is, that the TAB-Key event is either not recognized or simply ignored. At least, nothing happens... But if i use another key Alt (KeyCode.TAB), everything works.
    Does the TAB-Key needs to be handled differently from other KeyEvents?
    Thanks,
    J. Ishikawa
    Edited by: J. Ishikawa on Jun 7, 2013 6:55 PM

    Usually the tab key is used to move the focus to the next tab stop. So add borderPane.requestFocus() statement to the handleAction method
    if you want to get the tab event code when the BorderPane layout container is focused.
    import java.net.URL;
    import java.util.ResourceBundle;
    import javafx.event.ActionEvent;
    import javafx.fxml.FXML;
    import javafx.fxml.Initializable;
    import javafx.scene.control.Label;
    import javafx.scene.input.KeyEvent;
    import javafx.scene.layout.BorderPane;
    public class SampleController implements Initializable {
        @FXML
        BorderPane borderPane;
        @FXML
        private void handleAction(KeyEvent event) {
            borderPane.requestFocus();             
            System.out.println("You pressed me! " + event.getCode());
        @Override
        public void initialize(URL url, ResourceBundle rb) {
    }

  • KeyStroke Event Handler Registration

    Any idea why the two cases in the sample code below have different output??? The different key registration methods seem to work for other keystrokes like ctrl-v and ctrl-c, but not Home and End.:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Main{
    public static void main(String args[]){
    JFrame jf = new JFrame("Java Bug Test");
    jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    jf.setBounds(30,30, 300, 300);
    JTable jt = new JTable(5,5);
    jf.getContentPane().add(jt,BorderLayout.CENTER);
    KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_HOME,0);
    String actionName = "Home";
    * In CASE ONE, the handler prints "null".
    * In CASE TWO, the handler prints "Home".
    //Comment out for CASE TWO, Uncomment for CASE ONE. (currently setup for CASE ONE).
    jt.getInputMap().put(ks,actionName);
    jt.getActionMap().put(actionName, new Handler());
    //Comment out for CASE ONE, Uncomment for CASE TWO. (currently setup for CASE ONE).
    //jt.registerKeyboardAction(new Handler(),actionName,ks,JComponent.WHEN_FOCUSED); //Comment
    jf.setVisible(true);
    static class Handler extends AbstractAction{
    public void actionPerformed(ActionEvent ae){
    System.out.println(ae.getActionCommand());
    }

    when my thread starts running the keylistener is not working.

Maybe you are looking for

  • Printer driver for HP Laserjet m1132

    I've recently switched to a mac with everything updated (version 10.9.5) and I'm trying to install a driver for printer laserjet m1132. I followed each and every steps: system preference > printers and scanners > selected + > (selected the printer) 

  • Enhancements vendor/customer master data

    Hi, Are enhancements aboutvendor/customer master data there to allow to insert 55 digit into field 'Name' (ADDR1_DATA-NAME1) ? Now the ADDR1_DATA-NAME1 is 40 char. Any assistance would be greatly appreciated. Best Regards. Helen.

  • Validation in f-48 for reference key field mandatory

    Hi, please help in Validation Prerequisite for validation of reference key field mandatory in f-48 for particular user Regards, Mahendra

  • Windows 2008 R2 cross domain shared/security folder permissions

    I have a Windows 2008 R2 server located in the example.com domain.  I have a folder that's shared out and it needs to be accessed by a group of machines that are not in the same domain, they are part of a different domain. I made sure to give Everyon

  • (DII) Client Example - - missing class error

    To jump into DII, I have copied the source for the "Dynamic Invocation Interface (DII) Client Example" into a new class created in netbeans. The api jar for JAX-RPC has been mounted in the environment. The example compiles fine, but upon execute the