Search code examples
javaevent-handlingkeyevent

i am getting partial output to the following code


Since im a real noob to programming , i was trying to work out this code and i m getting a partial output. The idea was to print the character typed on the applet and if alt or shift key is pressed, it must be displayed in the status bar. The problem is there is no response on the applet but on pressing alt or shift key, i get the appropriate response on the status bar. here is the code:

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

/* <applet code="MyKeyApplet.class"
           width = "400"
           height = "400">
   </applet>*/

public class MyKeyApplet extends Applet implements KeyListener{
    char ch;
    String str=" ";

    public void init(){
        this.addKeyListener(this);
        requestFocus();
    }

    public void keyPressed(KeyEvent k){
        int x = k.getKeyCode();
        if(x==KeyEvent.VK_SHIFT)
            showStatus("You pressed Shift Key");
        else if (x==KeyEvent.VK_ALT)
            showStatus("You pressed Alt Key");
    }

    public void paint(Graphics g){
        g.drawString(str,40,40);
    }

    public void keyTyped(KeyEvent k){
        ch=k.getKeyChar();
        str="You Pressed" + ch;
        repaint();
    }

    public void keyReleased(KeyEvent k){
    }

}   

Solution

  • Haven't tested myself, but this answer might be helpful: https://stackoverflow.com/a/12483507/877472

    From what I can tell in your code, you're only ever checking for the modifier key presses (ctrl, alt, shift, etc), but you are not handling any situation for other keys. Again, I haven't tested this, but you might want to modify your code so that you have two separate handling actions: one for checking if the modifier key is pressed, and then afterwards another for handling ANY key press that is not a modifier. Something like this:

    public void keyPressed(KeyEvent k){
        int x = k.getKeyCode();
        if(x==KeyEvent.VK_SHIFT)
            showStatus("You pressed Shift Key");
        else if (x==KeyEvent.VK_ALT)
            showStatus("You pressed Alt Key");
        else
          str += k.getKeyChar(); // Add the pressed key to the string.
    }
    

    By the by, while I'm not 100% clear on what your program should be doing, however if you plan to continuously build a string, you might find better performance using the StringBuffer class.