2012-11-28 56 views
0

我想創建一個虛擬的數字鍵盤,所以,當我按下ü我得到,產生,Ø產生,依此類推:如何重新映射某些鍵?

789   789 
uio becomes 456 
jkl   123 
m    0 

但我需要鍵盤的其餘部分繼續照常工作。我試過this和一些其他的解決方案,但它們對我沒用,因爲在我的JTextField上,我得到了4U5I6O(或U4I5O6,這取決於我實現的解決方案)。

我需要擺脫這封信,並只產生數字。

有沒有人知道一個合適的解決方案?

謝謝。

+0

你的鍵盤事件處理程序不能單獨輸出你的信件,並且對它們採取行動,就像數字被按下一樣? – Miquel

回答

3

如果您直接輸入JTextField,那麼我建議使用DocumentFilter

由於DocumentFilter示例,請參見:

+0

我嘗試了建議的解決方案,但過濾器中的方法從不被調用,因此,我在我的文本中獲得了原始字母。 – ilvidel

+1

@ilvidel你用'setDocumentFilter()'設置過濾器嗎? –

+1

@ilvidel如果您嘗試過,請在您的問題中發佈SSCCE。這種方法應該可行,所以很可能你做錯了什麼 – Robin

1

這是@ Eng.Fouad的建議的eample(請,所有信貸給他)。

基本上,這將用隨機字符替換所有輸入到文本字段的文本。

我不難更新代碼以提供映射的更改(例如a = 1)甚至是加密過程。

public class TestPhasicDocumentFilter { 

    public static void main(String[] args) { 
     new TestPhasicDocumentFilter(); 
    } 

    public TestPhasicDocumentFilter() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       JFrame frame = new JFrame(); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(new PhasicPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class PhasicPane extends JPanel { 

     public PhasicPane() { 

      setLayout(new GridBagLayout()); 
      JTextField field = new JTextField(12); 
      add(field); 

      ((AbstractDocument)field.getDocument()).setDocumentFilter(new PhasicDocumentFilter()); 

     } 

     public class PhasicDocumentFilter extends DocumentFilter { 
      protected String phasic(String text) { 

       StringBuilder sb = new StringBuilder(text); 
       for (int index = 0; index < sb.length(); index++) { 
        sb.setCharAt(index, (char)(33 + (int)Math.round(Math.random() * 93))); 
       } 

       return sb.toString(); 
      } 

      @Override 
      public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException { 
       super.insertString(fb, offset, phasic(text), attr); 
      } 

      @Override 
      public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { 
       super.replace(fb, offset, length, phasic(text), attrs); 
      } 

     } 

    } 

}