我一直在尝试这样做,以便在点击"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);
}
}
代码中缺少什么?
答案 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);
}
}