How to get the value of a JComboBox?

0

I need to add to a vector the names that are chosen from several JComboBox, but I do not know how to do it.

try it with these two methods:   // To get the name that is selected   public String getName1 () {

guiID.getCBNombre1().addItemListener(new ItemListener(){ //addItemListener, para que los items puedan ser escuchados

  public void itemStateChanged(ItemEvent evento){

    if(evento.getStateChange()==ItemEvent.SELECTED){
      nombre = guiID.jugadoresSecundarios(guiID.perdido,guiID.vectorNombres)[guiID.getCBNombre1().getSelectedIndex()];
    }
  }
});

return nombre;

}

public String [] getLocateCampos (int cantJ) {

String campSelec[] = new String[cantJ];

while(cantJ>0){
  if(cantJ==4){
    campSelec[3]=getNombre4();
  }else if(cantJ==3){
    campSelec[2]=getNombre3();
  }else if(cantJ==2){
    campSelec[1]=getNombre2();
  }else if(cantJ==1){
    campSelec[0]=getNombre1();
  }
  cantJ--;
}

return campSelec;

}

    
asked by Roberto Rojas 25.11.2017 в 22:07
source

1 answer

0

How about, I understand that in your case you want to use the content of the JComboBox, I'll give you an example of how to directly take the value of the String of the selected item. Copy and peg in a class that is named Panel , then give "Run as java Application" , and change the selector to see how it works.

import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Panel {

    private JFrame frame;
    private JPanel panel;
    private JLabel label;
    private JComboBox<String> combo; // Si le quitás el parametrizado va a tomar como Object
    private String[] names;

    public Panel() {

        /*
         * Declaramos afuera del método e inicializamos adentro para reutilizar la
         * variable si queremos en otro método
         */
        names = new String[] { "Marcelo", "Roberto", "Lucas", "Gisella", "Ismael", "Mauricio" };
        label = new JLabel("Acá se van a imprimir los resultados");
        frame = new JFrame();
        panel = new JPanel();

        /*
         * Inicializamos el JComboBox parametrizado o no, osea JComboBox<String>, le
         * decimos que lo que va a recibir es un String, qué pasa si no se lo ponés?,
         * nada, lo toma como si fuera un Object y en teoría tarda más en devolver el
         * contenido porque primero averigua de qué tipo de dato está recibiendo
         */
        combo = new JComboBox<String>(names);

        BorderLayout borderLayout = new BorderLayout();
        frame.setLayout(borderLayout);
        frame.setTitle("Change JComboBox value");
        frame.add(panel);
        panel.add(combo, BorderLayout.NORTH);
        panel.add(label, BorderLayout.SOUTH);
        frame.setBounds(100, 100, 250, 150);
        frame.setVisible(true);

        /* Metemos la interfaz directamente dentro del botón, sin implementar nada */
        /*
         * LAMBDA:
         * Esta manera sólo va a solucionar tu consulta muy rápidamente con un copia y
         * pega, en el código de abajo hay una forma más simple, ésta es através de
         * lambda que es mas moderno y corto de escribir, te recomiendo que veas también
         * el código de alternativo
         * 
         * Parámetro : event tipo ItemEven aunque no esté declarado Cuerpo: Un
         * condicional y una acción hacia el JLabel.
         */

        combo.addItemListener(event -> {
            if (event.getStateChange() == ItemEvent.SELECTED) {
                label.setText(event.getItem().toString());
            }
        });

    }

    /* Método inicializador de App */
    public static void main(String[] args) {

        /* Creamos el panel con el setVisible() en su constructor */
        Panel p = new Panel();

    }

}

This is another way of doing it, it is perhaps longer, for a few lines and a few more characters, however is the most classic way , without using lambda, I recommend that you apply this last option or the next one.

import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


/*
 * Acá implementamos la interface, tiene sólo un método por eso pudimos usar
 * lambda anteriormente.
 */
public class Panel implements ItemListener {

    private JFrame frame;
    private JPanel panel;
    private JLabel label;
    private JComboBox<String> combo; // Si le quitás el parametrizado va a tomar como Object
    private String[] names;

    public Panel() {

        /*
         * Declaramos afuera del método e inicializamos adentro para reutilizar la
         * variable si queremos en otro método
         */
        names = new String[] { "Marcelo", "Roberto", "Lucas", "Gisella", "Ismael", "Mauricio" };
        label = new JLabel("Acá se van a imprimir los resultados");
        frame = new JFrame();
        panel = new JPanel();

        /*
         * Inicializamos el JComboBox parametrizado o no, osea JComboBox<String>, le
         * decimos que lo que va a recibir es un String, qué pasa si no se lo ponés?,
         * nada, lo toma como si fuera un Object y en teoría tarda más en devolver el
         * contenido porque primero averigua de qué tipo de dato está recibiendo
         */
        combo = new JComboBox<String>(names);

        BorderLayout borderLayout = new BorderLayout();
        frame.setLayout(borderLayout);
        frame.setTitle("Change JComboBox value");
        frame.add(panel);
        panel.add(combo, BorderLayout.NORTH);
        panel.add(label, BorderLayout.SOUTH);
        frame.setBounds(100, 100, 250, 150);
        frame.setVisible(true);

        /* Tenemos que agregar ésta línea indicandole al código que ése JComboBox espera una acción */
        combo.addItemListener(this);
    }

    /*
     * Esta es la forma clásica de hacerlo y te recomiendo que en principio la
     * aprendaas así, luego más adelante por lambda.
     * 
     * Parámetro : event tipo ItemEvent aunque no esté declarado
     * Cuerpo: Un condicional y una acción hacia el JLabel.
     */

    @Override
    public void itemStateChanged(ItemEvent event) {
        if (event.getStateChange() == ItemEvent.SELECTED) {
            label.setText(event.getItem().toString());
        }

    }

    /* Método inicializador de App */
    public static void main(String[] args) {

        /* Creamos el panel con el setVisible() en su constructor */
        Panel p = new Panel();

    }

}

This third form, would be using an anonymous class (in this case an interface would be) where inside the same button we give all the directives. An intermediate between the way to do it with Lambda and the other more classical, this way of doing it is very useful since there are few lines of code that we act within each JButton, JComboBox or another element, as well as we avoid putting conditional as if touch this button happens, as a counterpart and disadvantage is that it only applies to a particular element, and if we have several elements we have to make the same code to each one.

import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/*
 * Acá implementamos la interface, tiene sólo un método por eso pudimos usar
 * lambda anteriormente.
 */
public class Panel {

    private JFrame frame;
    private JPanel panel;
    private JLabel label;
    private JComboBox<String> combo; // Si le quitás el parametrizado va a tomar como Object
    private String[] names;

    public Panel() {

        /*
         * Declaramos afuera del método e inicializamos adentro para reutilizar la
         * variable si queremos en otro método
         */
        names = new String[] { "Marcelo", "Roberto", "Lucas", "Gisella", "Ismael", "Mauricio" };
        label = new JLabel("Acá se van a imprimir los resultados");
        frame = new JFrame();
        panel = new JPanel();

        /*
         * Inicializamos el JComboBox parametrizado o no, osea JComboBox<String>, le
         * decimos que lo que va a recibir es un String, qué pasa si no se lo ponés?,
         * nada, lo toma como si fuera un Object y en teoría tarda más en devolver el
         * contenido porque primero averigua de qué tipo de dato está recibiendo
         */
        combo = new JComboBox<String>(names);

        BorderLayout borderLayout = new BorderLayout();
        frame.setLayout(borderLayout);
        frame.setTitle("Change JComboBox value");
        frame.add(panel);
        panel.add(combo, BorderLayout.NORTH);
        panel.add(label, BorderLayout.SOUTH);
        frame.setBounds(100, 100, 250, 150);
        frame.setVisible(true);

        /*
         * De esta manera estamos decalrando y definiendo el evento dentro del mismo
         * JComboBox, no hay que declarar en una línea aparte qeu este elemento va a
         * recibir un evento. A su vez creamos una clase anónima (es una interfaz
         * anónima en este caso) y ahí mismo declaramos y definimos todo.
         */
        combo.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    label.setText(event.getItem().toString());
                }
            }
        });

    }

    /* Método inicializador de App */
    public static void main(String[] args) {

        /* Creamos el panel con el setVisible() en su constructor */
        Panel p = new Panel();

    }

}

Finally, if none of the three convinces you, you can change an internal line of the method that I passed to you and make it more readable, say:

        combo.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    /* Modificamos esta linea, ahora utilizamos getSelectedItem() y toString() */
                    label.setText(combo.getSelectedItem().toString());
                }
            }
        });

This way is more pleasant and intuitive when calling a String that is inside a JComboBox.

    
answered by 26.11.2017 / 14:04
source