无法获得requestFocus以按顺序关注JTextFields

时间:2014-04-09 11:36:42

标签: java jbutton jtextfield

我一直在尝试这样做,以便在点击"Next"按钮时,它会根据需要转到下一个JTextField,然后转到下一个,然后是下一个,依此类推。它只使用了一个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);
        }

    } 

代码中缺少什么?

1 个答案:

答案 0 :(得分: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);
    }
}