0

I am creating a singlish software.Don't think the word "Singlish" :-).

this is my code,

private void txt_titleKeyTyped(java.awt.event.KeyEvent evt) { 

char c = evt.getKeyChar();
         switch (c) {
            case 'a':
                txt_body.setText(txt_body.getText() + "අ");
                break;
            case 's':
                txt_body.setText(txt_body.getText() + "ස");
                break;
            }
 }

In this application ,when i am typing letter "a" program prints a specific character.I have two questions ,

  1. if I press letter "a" the program prints the correct character ("අ") and also prints "a"
    (like this "අa"). only I need "අ".how to prevent print "a".

  2. If i typed "aa" ,I need to print a another character.so I tried

       case 'aa':
          txt_body.setText(txt_body.getText() + "ආ");
          break;
    

    but there is a error "Unclosed character literal" Is there any way to assign two characters to a char like in javaScript.

Razib
  • 10,965
  • 11
  • 53
  • 80
jeewithe mal
  • 9
  • 1
  • 1
  • 3
  • 1
    I wouldn't think the word "Singlish" had you not mentioned it. And I have no idea what it means anyway. – Andy Turner May 05 '15 at 07:14
  • 1. you print `(txt_body.getText() + "ආ"` getText returns "a" because thats what the user pressed. 2. A Character can only hold one Character but you can use a Sting in a switch statement – Zion May 05 '15 at 07:27

2 Answers2

0

For the first question, I think you should remove the last char that gets printed in order to get rid of the undesired char, i.e.

...
char c = evt.getKeyChar();
int index = txt_body.getText().lastIndexOf(c);
if(index >= 0) {
   txt_body.setText(txt_body.getText().substring(0, index));
}
     switch (c) {
...

As for the second question, the answer is : You can't. What Javascript does is silently converting your char to a string, which is what you should do in Java too.

francesco foresti
  • 2,004
  • 20
  • 24
0

A character is a single letter, a data structure containing concatenation of characters is a string. In Java, you could do a switch statement on strings, as shown here, however, that being said, you have two problems:

  1. The txt_titleKeyTyped event will fire at each key press, meaning that typing aa will fire the same event twice.
  2. How do you intend to make your program differentiate between aa and two subsequent a characters?

You could have a timer which triggers after some time without key presses, say 500ms and tries to parse the string. You could then add evt.consume(); at the end to ensure that the typed character does not end up within the text box.

npinti
  • 51,780
  • 5
  • 72
  • 96