简体   繁体   中英

how to return to swing frame after clicking ok button of confirm dialog

Select a checkbox and check if text field related to it is filled with input

 chckbxDictionary = new JCheckBox();
 txtDictionaryStartPage = new JTextField();    
 JButton btnSubmit = new JButton("Submit");
 btnSubmit.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
      if(chckbxDictionary.isSelected()){
            if(txtDictionaryStartPage.getText().equals("")){
                    int type=JOptionPane.showConfirmDialog(null, "enter start page", "", JOptionPane.OK_CANCEL_OPTION);
                    if(type==JOptionPane.OK_OPTION){
                        //if ok return to frame and focus txtDictionaryStartPage for user input
                    }
                }
       }
  }
}

After clicking ok button on confirm dialog, I want to go back to jframe and focus the required text field for user to enter input and wait till input is entered.

Assuming they are in the same class, according to the JavaDoc :

public boolean requestFocusInWindow()

Requests that this Component gets the input focus. Refer to Component.requestFocusInWindow() for a complete description of this method. If you would like more information on focus, see How to Use the Focus Subsystem, a section in The Java Tutorial.

So in your case, you could do:

if(type==JOptionPane.OK_OPTION){
    txtDictionaryStartPage.requestFocusOnWindow();
}

If they are in same class, you can do:

 chckbxDictionary = new JCheckBox();
 txtDictionaryStartPage = new JTextField();    
 JButton btnSubmit = new JButton("Submit");
 btnSubmit.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
      if(chckbxDictionary.isSelected()){
            if(txtDictionaryStartPage.getText().equals("")){
                    int type=JOptionPane.showConfirmDialog(null, "enter start page", "", JOptionPane.OK_CANCEL_OPTION);
                    if(type==JOptionPane.OK_OPTION){
                        txtDictionaryStartPage.requestFocusInWindow();
                        frame.setVisible(true);
                    }
                }
       }
  }
}

I am not sure that the part frame.setVisible(true); is required, but try. If you put that in your code, it doesn't hurt anyway.

first argument to showConfirmDialog should be changed from null , to btnSubmit

int type=JOptionPane.showConfirmDialog(btnSubmit, "enter start page", "", JOptionPane.OK_CANCEL_OPTION);
if(type==JOptionPane.OK_OPTION){
      txtDictionaryStartPage.requestFocusOnWindow();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM