2012-07-25 26 views

回答

1

以下是你想要的。基本上,當按下.它增加了KeyListenerFocusListener通過他們Text部件和圓:

public class TestClass 
{ 
    private static int counter = 0; 

    public static void main(String[] args) 
    { 
     Display display = Display.getDefault(); 
     Shell shell = new Shell(display); 

     shell.setLayout(new FillLayout()); 

     /* These are the text fields */ 
     final Text textOne = new Text(shell, SWT.BORDER); 
     final Text textTwo = new Text(shell, SWT.BORDER); 
     final Text textThree = new Text(shell, SWT.BORDER); 

     /* Save them in an arraylist */ 
     final ArrayList<Text> textFields = new ArrayList<Text>(); 
     textFields.add(textOne); 
     textFields.add(textTwo); 
     textFields.add(textThree); 

     /* save their position as well (not optimal, you can think of an easier method) */ 
     final HashMap<Text, Integer> textFieldsMapping = new HashMap<Text, Integer>(); 
     textFieldsMapping.put(textOne, 0); 
     textFieldsMapping.put(textTwo, 1); 
     textFieldsMapping.put(textThree, 2); 

     /* Define keylistener which takes care of using . as tab */ 
     KeyListener keyListener = new KeyListener() { 

      @Override 
      public void keyReleased(KeyEvent arg0) { 
      } 

      @Override 
      public void keyPressed(KeyEvent arg0) { 
       /* if '.' pressed */ 
       if(arg0.character == '.') 
       { 
        /* ignore this action */ 
        arg0.doit = false; 

        /* get next text field */ 
        Text next = textFields.get(counter); 

        /* force focus on this text field */ 
        next.setFocus(); 
        next.forceFocus(); 
       } 
      } 
     }; 

     /* Define focuslistener which sets current position */ 
     FocusListener focusListener = new FocusListener() { 

      @Override 
      public void focusLost(FocusEvent arg0) { 
      } 

      @Override 
      public void focusGained(FocusEvent arg0) { 
       /* get current text field */ 
       Text current = (Text)arg0.getSource(); 

       /* get current position */ 
       int currentPosition = textFieldsMapping.get(current); 

       /* set counter to next text field */ 
       counter = (currentPosition + 1) % textFields.size(); 
      } 
     }; 

     /* add keylistener to text fields */ 
     textOne.addKeyListener(keyListener); 
     textTwo.addKeyListener(keyListener); 
     textThree.addKeyListener(keyListener); 

     /* add focuslistener to text fields */ 
     textOne.addFocusListener(focusListener); 
     textTwo.addFocusListener(focusListener); 
     textThree.addFocusListener(focusListener); 

     shell.pack(); 
     shell.open(); 
     while (!shell.isDisposed()) { 
      if (!display.readAndDispatch()) 
       display.sleep(); 
     } 
    } 
} 
+0

謝謝!我最初試圖找到一種方法來調用在Tab鍵被按下時發生的相同過程,但沒有用這種方法。似乎將重點直接放在下一個控制上是一條路。您是否知道調用選項卡邏輯的方法? 因爲我發佈了,我找到了VerifyListener類。通過向控件添加驗證監聽器,我可以攔截'。'。事件並將焦點設置到下一個字段。 – 2012-07-26 13:18:18

相關問題