5

I am building a GUI where one textfield must be typed in latin characters, the others in arabic. To avoid switching the keyboard layout, I choosed to maintain it in arabic and use a DocumentFilter in that particular textfield to replace arabic characters with their counterpart according to a latin azerty layout. Example, if one types '\u0628' (it is 'ب'), this should be printed 'F' because in they are in same key. This worked fine with all characters except with the B key, which translates into two characters "لا" in the arabic layout, and the DocumentFilter.replace is called two times for each character. Is there a way to control the size of text argument when replace is called? any other solution to the problem?

Here is my original DocumentFilter.replace code

...
private static char[] latin = {'A','Z','E','R','T','Y','U','I','O','P',...};
private static char[] arabic = {'\u0636','\u0635','\u062B','\u0642','\u0641',...};
...    
(PlainDocument) txtFileId.getDocument().setDocumentFilter(new DocumentFilter() {
    @Override
    public void replace(DocumentFilter.FilterBypass fb, int offset,int length, String text, AttributeSet attr) throws BadLocationException {
    StringBuilder sb = new StringBuilder();
    int i=0;
    if (text.length()==1) {
        while (text.charAt(0)!=arabic[i] && i<arabic.length)
        i++;
    if (text.charAt(0)==arabic[i])
        sb.append(latin[i]);
    }
    if (text.length()==2) {
        if (text.equals(new String(new char[]{'\u0627','\u0644'})))
        sb.append('B');
    }
    super.insertString(fb, offset, sb.toString(), attr);
}

Thanks you!

Brahim Gaabab
  • 190
  • 1
  • 7

1 Answers1

0

How about creating a global variable to keep track of whether your callback has been called for this B event? It can be a simple Boolean flag that flips each time the B event is generated. You only output B when the flag is true.