Search code examples
javastringjframejoptionpane

How to open a JFrame from another class


I want the program to open the JFrame which has a dialog box within it, currently when I try to open userFileSelected it opens the main JFrame which usually shows the contents of the file input but I want the program the open the JFrame with the dialog box so the user can enter the file first and then the program opens the file which has been entered.

Can someone help me figure out how I could possibly open JFrame with the dialog box first and then open the rest of the program.

Class with the JFrame taking the user input:

public class userFileSelected extends JFrame implements ActionListener, KeyListener {

    public static void main(String[] args) {


    JFrame parent = new JFrame();
    String selectedFile;
    selectedFile = JOptionPane.showInputDialog(parent, "Input file name");
    String selectedFile1 = selectedFile;
    selectedRequirement = selectedFile1;
    }

Where I want the class to be called:

    @Override
    public void actionPerformed(ActionEvent ae) {
        if ("FileInput".equals(ae.getActionCommand())) {
            userFileSelected ufs = new userFileSelected();
        }

Solution

  • If I understood your question correctly, add an if/else statement to your app's initialization method. If a file has been selected then frame.setVisible(false). And you can initialize the JFrame seprately if you declare it as public. so your code would look like:

    public class userFileSelected extends JFrame implements ActionListener, KeyListener {
    //populate this field however you see fit
    private boolean fileSelected;
    //public JFrame so other classes can make modifications.
    public JFrame parent = new JFrame();
    public static void main(String[] args) {
    String selectedFile;
    selectedFile = JOptionPane.showInputDialog(parent, "Input file name");
    String selectedFile1 = selectedFile;
    selectedRequirement = selectedFile1;
    
    if (fileSelected) {
       parent.setVisible(false);
    }
    else {
      parent.setVisible(true);
       }
    }