Note that there are some explanatory texts on larger screens.

plurals
  1. POKeyEvent not functioning for JTextArea, but works for the JFrame containing the JTextArea
    primarykey
    data
    text
    <p>I searched for answers, but all i found is workaounds, not the reason, so i am asking this question:</p> <p>I am new to GUI programming. While practicing some code regarding key event handling, i came accross an example that has a JTextArea contained inside a JFrame. The keylistener interface is implemented by the Frame itself. When a key is pressed some relevant information are shown on the text area based on the key pressed. the code works fine.</p> <p>but i tried to go differently and tried to register the JTextarea to a keyListenr instead of the JFrame. However, this does not respond to key events. Here is the code below. Please help.</p> <pre><code>public class KeyDemoFrame extends JFrame { private String line1 = ""; private String line2 = ""; private String line3 = ""; private JTextArea textArea; public KeyDemoFrame() { super("Demonstrating Keystrong events"); textArea = new JTextArea(10,21); textArea.setText("Press any key on keyboard"); textArea.setEnabled(false); textArea.setDisabledTextColor(Color.BLACK); add(textArea); //addKeyListener( this ); KeyEventHandler keyStrokeHandler = new KeyEventHandler(); addKeyListener(keyStrokeHandler); } private class KeyEventHandler implements KeyListener { public void keyPressed(KeyEvent event) { line1 = String.format("Your pressed the %s key", KeyEvent.getKeyText(event.getKeyCode())); setLines2and3(event); } public void keyReleased(KeyEvent event) { line1 = String.format("You released %s key", KeyEvent.getKeyText(event.getKeyCode())); setLines2and3(event); } public void keyTyped(KeyEvent event) { line1 = String.format("You typed %s key",KeyEvent.getKeyText(event.getKeyCode())); setLines2and3(event); } private void setLines2and3(KeyEvent event) { line2 = String.format("This key is %san action key", (event.isActionKey()?"":"not ")); String temp = KeyEvent.getKeyModifiersText( event.getModifiers() ); line3 = String.format( "Modifier keys pressed: %s",( temp.equals( "" ) ? "none" : temp ) ); textArea.setText( String.format( "%s\n%s\n%s\n",line1, line2, line3 ) ); } } </code></pre> <p>}</p> <pre><code>import javax.swing.JFrame; public class KeyDemo { public static void main(String[] args) { KeyDemoFrame keyDemoFrame = new KeyDemoFrame(); keyDemoFrame.setSize(300, 100); keyDemoFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); keyDemoFrame.setVisible(true); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload