This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
Consume it if it is not need...
Posted by Kishori Sharan on October 24, 2000 at 4:23 PM
Hi I have tried it with JTextArea and it doesn't write the character f in JTextArea when you type in Alt + f. The following program Test.java illustrates it. You can also use consume ( ) method on KeyEvent object within your keyTyped so that when Alt key is pressed in JTextArea/TextArea then no character is typed in it. public void keyTyped ( KeyEvent e ) { if ( e.isAltDown ( ) ) { e.consume ( ) ; } } This will prevent any character from being written in the TextArea. I have tested this code with awt TextArea too and it works. The following program is using Swing which automatically handles when Alt key and any other key combination. That is, when you press any key when Alt key is pressed then in JtextArea nothing is typed as you are getting in TextArea. Thanx Kishori /////////////////////// Test.java import java.awt.*; import java.awt.event.*; import java.applet.* ; import javax.swing.* ; public class Test extends JFrame implements KeyListener { JTextField tf = new JTextField ( "Waiting for response" ) ; JTextArea ta = new JTextArea ( 10, 10 ) ; JPanel panel = new JPanel ( ) ; public Test ( ) { Container cp = getContentPane ( ) ; panel.add ( tf ) ; panel.add ( ta ) ; cp.add ( panel ) ; ta.addKeyListener ( this ) ; // Add Menu to the frame JMenuBar menuBar = new JMenuBar ( ) ; setJMenuBar ( menuBar ) ; // Create the file menu JMenu file = new JMenu ( "File" ) ; file.setMnemonic(KeyEvent.VK_F); JMenuItem open = new JMenuItem ( "Open" , KeyEvent.VK_O ) ; JMenuItem exit = new JMenuItem ( "Exit" , KeyEvent.VK_E ) ; file.add ( open ) ; file.add ( exit ) ; menuBar.add ( file ) ; } public void keyPressed ( KeyEvent e ) { if ( e.getKeyCode ( ) == KeyEvent.VK_ALT ) { tf.setText ( " Alt key is pressed" ) ; } } public void keyTyped ( KeyEvent e ) { //if ( e.isAltDown ( ) ) { // tf.setText ( " Alt was down" ) ; //} if ( e.getKeyChar ( ) == 'a' ) { tf.setText ( " A is pressed" ) ; e.consume ( ) ; } } public void keyReleased ( KeyEvent e ) { } public static void main ( String[] args ) { Test f = new Test ( ) ; f.setBounds ( 100,100, 500, 500 ) ; f.show ( ) ; } }
Replies:
- Thanks Ujjwal October 28, 2000 at 2:25 PM
(0)
|