Show array by JOptionPane and pick up result

2

I have a problem. I want to show an array in a JOptionPane, I do it like that.

String[] continentes = { "ANorte", "ASur", "Africa", "Europa", "Asia", "Oceania" };
JOptionPane.showMessageDialog(null, Arrays.toString(continentes)); 

So, I show the array by the JOptionPane, but the problem is when I want to enter one of those values, or another, I'll take care of making an exception.

To collect a piece of information from a JOptionPane, I usually do this:

String aux= JOptionPane.showInputDialog("Introduce algo");

And now, aux, it has a string with what you have entered, but if I put:

String aux = JOptionPane.showMessageDialog(null, Arrays.toString(continentes)); 

I get this error,

  

Type mismatch: can not convert from void to String []

and I do not know how to solve it. I want a square to appear to enter a name and be able to pick it up.

I thank everyone, it will surely be a very simple mistake, but I have not found anything.

    
asked by cupax64 16.12.2018 в 22:14
source

1 answer

5

showMessageDialog will not return anything (since your signature indicates that the return type is Void.) remember that showMessageDialog is only to display a message. what you want to do is a showInputDialog with Options, therefore:

Taking the Oracle Tutorial as a Reference Regarding Jdialogs link here

we have to: showInputDialog is what we want to use. given your need we have options:

  

String[] continentes = { "ANorte", "ASur", "Africa", "Europa", "Asia", "Oceania" };

String[] continentes = {"ANorte", "ASur", "Africa", "Europa", "Asia", "Oceania"};
/*
   JOptionPane.showInputDialog( <Ventana padre>,
   "mensaje a desplegar",
   "titulo de la ventana",
    Tipo de JoptionPane,
    Icono,
    Opciones,
    Opcion default);
*/
Object selection = JOptionPane.showInputDialog(null,"Elija un Continente",
"Seleccion",JOptionPane.QUESTION_MESSAGE,null,continentes,null);
//si se cierra la ventan o le da cancel el objecto selection es nulo por tanto verificar eso
if(Objects.isNull(selection)){
    System.out.println("opcion invalida!");
}else{
    System.out.printf("opcion elegida: %s",selection);
    System.out.println();
} 

and this will look like this:

Important considerations: JOptionPane.showInputDialog returns a Object therefore it must be verified that it is not null and when it is used it is String (which is very probable but not guaranteed.)

    
answered by 17.12.2018 в 02:14