2014-04-09 2 views
0

"Next" 버튼을 클릭하면 필요에 따라 다음 JTextField으로 이동 한 후 다음, 다음 등으로 이동하려고했습니다. . requestFocus() 하나만 사용했지만 에 코드를 추가하여 각자 JTextFields에 코드를 요청하여 마지막으로 요청 된 포커스로 곧바로 이동합니다. 아래 코드 :requestFocus를 통해 JTextFields에 순차적으로 초점을 맞출 수 없음

//adds functionality to the next button 
     next.addActionListener(new ActionListener(){ 
    @Override 
    public void actionPerformed(ActionEvent e){ 
     //creates a file for the next button output 
     final File file = new File("NextOutput.txt"); 
     //creates a printwriter to output to file everytime next button is clicked (overwrite) 
     try (PrintWriter output = new PrintWriter(new FileWriter(file))) { 
      String s = fName.getText(); 
      output.print(s + " "); 
      lName.requestFocus(); 
      String s1 = lName.getText(); 
      output.append(s1 + " "); 
      sNumber.requestFocus(); 
      String s2 = sNumber.getText(); 
      output.append(s2 + " "); 
      lResults.requestFocus(); 
      String s3 = lResults.getText(); 
      output.append(s3 + " "); 


     } catch (IOException ex) { 
      Logger.getLogger(MyProgram.class.getName()).log(Level.SEVERE, null, ex); 
     } 

    } 

코드에 무엇이 누락 되었습니까?

답변

0

먼저 초점을 소유 한 TextField을 확인한 후 다음 필드에 초점을 요청하십시오. 이 접근 방식에서는 lName에 초점을 요청하고 sNumber에 초점을 맞추면 lResult이됩니다.

public void actionPerformed(ActionEvent e) { 
    //creates a file for the next button output 
    final File file = new File("NextOutput.txt"); 
    //creates a printwriter to output to file everytime next button is clicked (overwrite) 
    boolean lNameFocus = lName.isFocusOwner(); 
    boolean sNumberFocus = sNumber.isFocusOwner(); 
    boolean fNameFocus = fName.isFocusOwner(); 
    boolean lResultsFocus = lResults.isFocusOwner(); 

    try (PrintWriter output = new PrintWriter(new FileWriter(file))) { 
     //If none of the fields is owning the focus then lName requests the focus 
     if (!(lNameFocus && sNumberFocus && fNameFocus && lResultsFocus)) { 
      String s = fName.getText(); 
      output.print(s + " "); 
      lName.requestFocus(); 
     //if lName is owning the focus then sNumber should be next to request 
     } else if (lNameFocus) { 
      String s1 = lName.getText(); 
      output.append(s1 + " "); 
      sNumber.requestFocus(); 
     // and so on 
     } else if (sNumberFocus) { 
      String s2 = sNumber.getText(); 
      output.append(s2 + " "); 
      lResults.requestFocus(); 
      String s3 = lResults.getText(); 
      output.append(s3 + " "); 
     } 

    } catch (IOException ex) { 
     Logger.getLogger(MyProgram.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 
관련 문제