Foros del Web » Programación para mayores de 30 ;) » Java »

[SOLUCIONADO] addItem en JComboBox

Estas en el tema de addItem en JComboBox en el foro de Java en Foros del Web. Buenas tardes, tengo un JComboBox en el que se muestran unas claves. Si selecciono alguna, nos muestran en unos JTextField los valores correctamente a través ...
  #1 (permalink)  
Antiguo 08/08/2014, 08:09
Avatar de elpivelardin  
Fecha de Ingreso: agosto-2014
Mensajes: 8
Antigüedad: 9 años, 8 meses
Puntos: 0
addItem en JComboBox

Buenas tardes,

tengo un JComboBox en el que se muestran unas claves. Si selecciono alguna, nos muestran en unos JTextField los valores correctamente a través de un ActionListener

Mi duda es cuando hago un addItem al JComboBox me muestra automáticamente los valores en los JTextField.

Hay alguna manera de evitar eso?

Gracias y un saludo.
  #2 (permalink)  
Antiguo 11/08/2014, 09:20
Avatar de farfamorA  
Fecha de Ingreso: noviembre-2010
Ubicación: Lima
Mensajes: 136
Antigüedad: 13 años, 5 meses
Puntos: 24
Respuesta: addItem en JComboBox

Debes mostrar un poco de tu código para ayudarte...
  #3 (permalink)  
Antiguo 11/08/2014, 09:32
Avatar de elpivelardin  
Fecha de Ingreso: agosto-2014
Mensajes: 8
Antigüedad: 9 años, 8 meses
Puntos: 0
Respuesta: addItem en JComboBox

Tengo un JFrame con 3 pestañas para la gestion de alumnos, guardando los datos en una tabla de MySQL. al dar de alta un alumno o recuperar los alumnos de la tabla, hago un additem para refrescar un jcombobox que hay tanto en la pestaña de bajas como modificaciones, pero al añadir se activa el actionListener y me muestra los datos de lo añadido automáticamente, sin necesidad de pulsar en el jcombobox

Este es el codigo de Altas

Código:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;

import java.sql.*;

public class PanelAltas extends JPanel implements ActionListener{

	private static final long serialVersionUID = 1L;
	private JTextField clave = new JTextField();
	private JTextField nombre = new JTextField();
	private JTextField apellidos = new JTextField();
	private JTextField edad = new JTextField();
	private JTextField calle = new JTextField();
	private JTextField numero = new JTextField();
	private JTextField cp = new JTextField();
	
	private JButton limpiar = null;
	private JButton alta = null;
		
	public PanelAltas(){
				
		//configuracion JPanel
		this.setLayout(new BorderLayout());
		
		//parte de datos personales + direccion
		JPanel panel1 = new JPanel();
		panel1.setLayout(new GridLayout(4,4));
		panel1.setBorder(new TitledBorder("Datos personales:"));
		
		panel1.add(new JLabel("Clave"));
		clave.setHorizontalAlignment(SwingConstants.RIGHT);
		panel1.add(clave);
		
		panel1.add(new JLabel("Nombre"));
		nombre.setHorizontalAlignment(SwingConstants.RIGHT);
		panel1.add(nombre);
		
		panel1.add(new JLabel("Apellidos"));
		apellidos.setHorizontalAlignment(SwingConstants.RIGHT);
		panel1.add(apellidos);
		
		panel1.add(new JLabel("Edad"));
		edad.setHorizontalAlignment(SwingConstants.RIGHT);
		panel1.add(edad);
		
		this.add(panel1,BorderLayout.NORTH);
		
		panel1 = new JPanel();
		panel1.setLayout(new GridLayout(3,3));
		panel1.setBorder(new TitledBorder("Dirección:"));
		
		panel1.add(new JLabel("Calle"));
		calle.setHorizontalAlignment(SwingConstants.RIGHT);
		panel1.add(calle);
		
		panel1.add(new JLabel("Número"));
		numero.setHorizontalAlignment(SwingConstants.RIGHT);
		panel1.add(numero);
		
		panel1.add(new JLabel("Código Postal"));
		cp.setHorizontalAlignment(SwingConstants.RIGHT);
		panel1.add(cp);
		
		this.add(panel1,BorderLayout.CENTER);
		
		//configuracion Jbutton
		panel1=new JPanel();
		panel1.setLayout(new FlowLayout());
		limpiar = new JButton("Limpiar");
		limpiar.setMnemonic('L');
		limpiar.addActionListener(this);
		panel1.add(limpiar);
		alta = new JButton("Dar de alta");
		alta.setMnemonic('D');
		alta.addActionListener(this);
		panel1.add(alta);
		
		this.add(panel1,BorderLayout.SOUTH);		
	}

	
	public void actionPerformed(ActionEvent ev) {
		String aux = ((JButton)ev.getSource()).getText();
		
		if(aux.equals("Limpiar"))	limpiar();
		else	alta();
	}
	
	public void limpiar(){
		
		clave.setText("");
		nombre.setText("");
		apellidos.setText("");
		edad.setText("");
		calle.setText("");
		numero.setText("");
		cp.setText("");
	}
	
	public void alta(){
		try{
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/gestion","root","root");
			PreparedStatement pstmt = con.prepareStatement("INSERT INTO alumnos VALUES(?,?,?,?,?,?,?)");
			pstmt.setString(1,clave.getText());
			pstmt.setString(2,nombre.getText());
			pstmt.setString(3,apellidos.getText());
			pstmt.setInt(4,Integer.parseInt(edad.getText()));
			pstmt.setString(5,calle.getText());
			pstmt.setInt(6,Integer.parseInt(numero.getText()));
			pstmt.setString(7,cp.getText());
			pstmt.executeUpdate();
			pstmt.close();
			con.close();
		}
		catch(ClassNotFoundException ex){ex.printStackTrace();}
		catch(SQLException ex){ex.printStackTrace();}
		PanelBajas.c.addItem(clave.getText());
		PanelModificaciones.cb.addItem(clave.getText());
		limpiar();
	}
}
Y este el de Bajas

Código:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;


public class PanelBajas extends JPanel implements ActionListener{

	private static final long serialVersionUID = 1L;
	private JTextField nombre = new JTextField();
	private JTextField apellidos = new JTextField();
	private JTextField edad = new JTextField();
	private JTextField calle = new JTextField();
	private JTextField numero = new JTextField();
	private JTextField cp = new JTextField();
	
	private JButton baja = null;
	
	static JComboBox<Object> c = null;
	
	public PanelBajas(){

		//configuracion JPanel
		this.setLayout(new BorderLayout());
		
		//configuracion apartado alumnos
		JPanel panel1 = new JPanel();
		panel1.setLayout(new GridLayout(1,1));
		panel1.setBorder(new TitledBorder("Alumnos:"));
		panel1.add(new JLabel("Clave"));
		c = new JComboBox<Object>();
		c.addActionListener(this);
		panel1.add(c);
		
		this.add(panel1,BorderLayout.NORTH);
		
		//parte de datos personales + direccion
		panel1 = new JPanel();
		panel1.setLayout(new GridLayout(2,0));
		JLabel aux = new JLabel();
		aux.setLayout(new GridLayout(3,3));
		aux.setBorder(new TitledBorder("Datos personales:"));
		
		aux.add(new JLabel("Nombre"));
		nombre.setHorizontalAlignment(SwingConstants.RIGHT);
		nombre.setEditable(false);
		aux.add(nombre);
		
		aux.add(new JLabel("Apellidos"));
		apellidos.setHorizontalAlignment(SwingConstants.RIGHT);
		apellidos.setEditable(false);
		aux.add(apellidos);
		
		aux.add(new JLabel("Edad"));
		edad.setHorizontalAlignment(SwingConstants.RIGHT);
		edad.setEditable(false);
		aux.add(edad);
		
		panel1.add(aux,BorderLayout.CENTER);
		
		aux = new JLabel();
		aux.setLayout(new GridLayout(3,3));
		aux.setBorder(new TitledBorder("Dirección:"));
		
		aux.add(new JLabel("Calle"));
		calle.setHorizontalAlignment(SwingConstants.RIGHT);
		calle.setEditable(false);
		aux.add(calle);
		
		aux.add(new JLabel("Número"));
		numero.setHorizontalAlignment(SwingConstants.RIGHT);
		numero.setEditable(false);
		aux.add(numero);
		
		aux.add(new JLabel("Código Postal"));
		cp.setHorizontalAlignment(SwingConstants.RIGHT);
		cp.setEditable(false);
		aux.add(cp);
		
		panel1.add(aux,BorderLayout.SOUTH);
		
		this.add(panel1,BorderLayout.CENTER);
		
		//configuracion Jbutton
		panel1=new JPanel();
		panel1.setLayout(new FlowLayout());
		baja  = new JButton("Dar de baja");
		baja.setMnemonic('D');
		baja.addActionListener(this);
		panel1.add(baja);
		
		this.add(panel1,BorderLayout.SOUTH);
		
	}
	
	public void actionPerformed(ActionEvent ev) {
		if(ev.getSource() instanceof JButton)	baja();
		if(ev.getSource() instanceof JComboBox)	consultar();
	}
	
	public void baja(){
		String x = (String) c.getSelectedItem();
		int indice = c.getSelectedIndex();
		
		try{
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/gestion","root","root");
			PreparedStatement pstmt = con.prepareStatement("DELETE FROM alumnos WHERE CLAVE=?");
			pstmt.setString(1,x);
			pstmt.executeUpdate();
			pstmt.close();
			con.close();
		}
		catch(ClassNotFoundException ex){ex.printStackTrace();}
		catch(SQLException ex){ex.printStackTrace();}
		
		c.removeItemAt(indice);
		PanelModificaciones.cb.removeItemAt(indice);
		
		limpiar();
	}
	
	public void limpiar(){
		
		nombre.setText("");
		apellidos.setText("");
		edad.setText("");
		calle.setText("");
		numero.setText("");
		cp.setText("");
	}
	
	public void consultar(){
		String x = (String) c.getSelectedItem();
		
		try{
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/gestion","root","root");
			PreparedStatement pstmt = con.prepareStatement("SELECT * FROM alumnos WHERE CLAVE=?");
			pstmt.setString(1,x);
			ResultSet rs = pstmt.executeQuery();
			while(rs.next()){
				nombre.setText(rs.getString(2));
				apellidos.setText(rs.getString(3));
				edad.setText(Integer.toString(rs.getInt(4)));
				calle.setText(rs.getString(5));
				numero.setText(Integer.toString(rs.getInt(6)));
				cp.setText(rs.getString(7));
			}
			rs.close();
			pstmt.close();
			con.close();
		}
		catch(ClassNotFoundException ex){ex.printStackTrace();}
		catch(SQLException ex){ex.printStackTrace();}
	}
}
Gracias.
  #4 (permalink)  
Antiguo 11/08/2014, 09:54
Avatar de farfamorA  
Fecha de Ingreso: noviembre-2010
Ubicación: Lima
Mensajes: 136
Antigüedad: 13 años, 5 meses
Puntos: 24
Respuesta: addItem en JComboBox

En vez de manejar el evento de selección de un Item del JComboBox con actionPerformed, utiliza itemListener.
Código Java:
Ver original
  1. miComboBox.addItemListener(new ItemListener() {
  2.     @Override
  3.     public void itemStateChanged(ItemEvent e) {
  4.         if (evt.getStateChange() == java.awt.event.ItemEvent.SELECTED) {
  5.             // tu lógica
  6.         }
  7.     }
  8. });
Ten en cuenta que ese evento se disparará para dos casos: cuando se seleccione un Item y cuando se deseleccione. Es por eso que incluyo el 'if' ahí, para que tu lógica se ejecute sólo cuando un Item es seleccionado.
Más info acá:
http://docs.oracle.com/javase/7/docs...mListener.html
http://docs.oracle.com/javase/7/docs...ItemEvent.html

Salu2.

Última edición por farfamorA; 11/08/2014 a las 09:56 Razón: Añadir documentación.
  #5 (permalink)  
Antiguo 11/08/2014, 10:02
Avatar de elpivelardin  
Fecha de Ingreso: agosto-2014
Mensajes: 8
Antigüedad: 9 años, 8 meses
Puntos: 0
Respuesta: addItem en JComboBox

Lo he probado y se sigue ejecutando, parece que al hacer el addItem se selecciona y lo cambia.

Voy a mirar los enlaces que me adjuntas, a ver si puedo evitar esto

Muchas gracias.
  #6 (permalink)  
Antiguo 11/08/2014, 10:29
Avatar de farfamorA  
Fecha de Ingreso: noviembre-2010
Ubicación: Lima
Mensajes: 136
Antigüedad: 13 años, 5 meses
Puntos: 24
Respuesta: addItem en JComboBox

Si estás manejando los eventos correctamente, el itemStateChanged (método del ItemListener) no debería invocarse.
Según la documentación:
Cita:
Invoked when an item has been selected or deselected by the user. The code written for this method performs the operations that need to occur when an item is selected (or deselected).
Te dejo un ejemplo listo para ejecutar:
Código Java:
Ver original
  1. package comboitemselect.ComboItemSelect;
  2.  
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.awt.event.ItemEvent;
  6. import java.awt.event.ItemListener;
  7. import javax.swing.JButton;
  8. import javax.swing.JComboBox;
  9. import javax.swing.JFrame;
  10. import javax.swing.JLabel;
  11.  
  12. /**
  13.  *
  14.  * @author farfamorA
  15.  */
  16. public class MyFrame extends JFrame {
  17.    
  18.     private final JButton myButton;
  19.     private JComboBox myComboBox;
  20.     private JLabel myLabel;
  21.    
  22.     public MyFrame() {
  23.        
  24.         myComboBox = new javax.swing.JComboBox();
  25.         myLabel = new javax.swing.JLabel();
  26.         myButton = new javax.swing.JButton();
  27.  
  28.         setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  29.         getContentPane().setLayout(new java.awt.FlowLayout());
  30.  
  31.         myComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
  32.         getContentPane().add(myComboBox);
  33.  
  34.         myLabel.setText("(Sin valor)");
  35.         getContentPane().add(myLabel);
  36.  
  37.         myButton.setText("Agregar");
  38.         getContentPane().add(myButton);
  39.  
  40.         pack();
  41.        
  42.         myComboBox.addItemListener(new ItemListener() {
  43.             @Override
  44.             public void itemStateChanged(ItemEvent e) {
  45.                 if (e.getStateChange() == java.awt.event.ItemEvent.SELECTED) {
  46.                     myLabel.setText(myComboBox.getSelectedItem().toString());
  47.                     System.out.println("myComboBox.itemStateChanged");
  48.                 }
  49.             }
  50.         });
  51.         myButton.addActionListener(new ActionListener() {
  52.             @Override
  53.             public void actionPerformed(ActionEvent e) {
  54.                 myComboBox.addItem("Item " + (myComboBox.getItemCount()+1));
  55.             }
  56.         });
  57.     }
  58.    
  59.     public static void main(String args[]) {
  60.         java.awt.EventQueue.invokeLater(new Runnable() {
  61.             @Override
  62.             public void run() {
  63.                 new MainFrame().setVisible(true);
  64.             }
  65.         });
  66.     }
  67.    
  68. }
Como verás, cuando se pulsa el botón, se añaden items al combo. Sin embargo, el evento de item seleccionado no se dispara sino hasta que efectivamente selecciones un item.
  #7 (permalink)  
Antiguo 12/08/2014, 05:13
Avatar de elpivelardin  
Fecha de Ingreso: agosto-2014
Mensajes: 8
Antigüedad: 9 años, 8 meses
Puntos: 0
Respuesta: addItem en JComboBox

Solucionado! Muchas gracias!

Etiquetas: actionlistener, jcombobox
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 03:48.