How to get out of Joptionpane without closing the Main window?

Asked

Viewed 167 times

0

I’m trying to create a program in Java Agenda, but when I leave the JOptionPane configuring the Agenda Owner name, called from the main window, the entire application is closed.

String nome = "";
do{
    nome = JOptionPane.showInputDialog(null, "Informe o proprietário da Agenda", "Cadastro de proprietário",WIDTH);
    if(nome == null){
        System.exit(0);
    }
    else if(nome.isEmpty()){
        JOptionPane.showMessageDialog(null, "Campo não pode estar vazio!");
    }
    else{
        Agenda agenda = new Agenda(nome);
        JOptionPane.showMessageDialog(null, "A agenda do "+agenda.getNome()+" foi criada com sucesso!");
    }
}while(nome.isEmpty());

I know the problem is in System.exit(0), but I don’t know how I could solve.

  • Is there any motivation to use a do while in that context ?

  • Present a [mcve] so that it is possible to test the code,

  • 1

    This form is very bad, there are other ways better and less repetitive than this, but you can not suggest anything better, without testing. Access the link above and provide a minimal example that allows us to test your code and simulate the problem.

  • I’ll improve the code to make it easier

  • @Franciscooliveira don’t forget the [mcve]

1 answer

0

I believe the choice of a do while was not the best in that scenario, because when the JOptionpane is closed, you already have this information in hand, which is the return of value.

If the goal is to ask the user for a value, until it is valid, a while:

public static void main(String[] args) {

    String nome = solicitarPropietario();

    while(nome == null || nome.isEmpty()) {
        JOptionPane.showMessageDialog(null, "Campo não pode estar vazio!");
        nome = solicitarPropietario();
    }

    Agenda agenda = new Agenda(nome);
    JOptionPane.showMessageDialog(null, "A agenda do " + agenda.getNome() + " foi criada com sucesso!");
}

public static String solicitarPropietario() {
    return JOptionPane.showInputDialog(null, "Informe o proprietário da Agenda", "Cadastro de proprietário");
}
  • Although valid, solutions based on this lot of joptionpane are terrible. This pollutes the application too much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.