Results 1 to 3 of 3

Thread: how to change keycode of KeyPressed Event and show result in JtextField

Threaded View

  1. #2
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418
    I gave this a shot but with not much luck. ActionEvent defines a bunch of constants SHIFT_MASK, CTRL_MASK ect.. but an action event is only fired off if the enter key is pressed, so say if the alt key is press the event is never fired off. The KeyEvent class defines the same kind of constants.
    Code:
      import java.awt.*; 
      import javax.swing.*;
      import java.awt.event.*;  
    
      public class Example{
       public static void main(String[] args){
         new Example("Example");  
       }
       private JFrame jf; 
       private JTextField jtf1; 
       private Container c;
      
       public Example(String title){
         jf = new JFrame(title); 
         c = jf.getContentPane();
         jtf1 = new JTextField(10);
         
         c.add(jtf1, BorderLayout.NORTH);
         
         jf.addWindowListener(new WindowMonitor()); 
         jtf1.addKeyListener(new KeyMonitor(jtf1));
         jtf1.addActionListener(new KeyMonitor(jtf1)); 
    
         jf.setSize(300,200);
         jf.setVisible(true);          
      }
     }
    
     class WindowMonitor extends WindowAdapter{
        public void windowClosing(WindowEvent we){
         System.exit(0);
      }
     }
    
     class KeyMonitor extends KeyAdapter implements ActionListener{
       JTextField jtf1;
    
       public KeyMonitor(JTextField jtf1){
        this.jtf1 = jtf1;
         
       }
      /*
       public void keyTyped(KeyEvent ke){ 
         if((ke.getID() == KeyEvent.KEY_TYPED) && (ke.getKeyCode() == KeyEvent.VK_SHIFT)){
            // not working
         }
       }
      */
       public void actionPerformed(ActionEvent ae){  
         if(ae.getID() == ActionEvent.SHIFT_MASK){
           // not working
         } 
        }
       }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width