How to fill a Java box combo from another class Using MySql

1

It turns out that I created a class with java interface in conjunction with NetBeans. Well I have a combo that filled it with the result of a query but when opening a new frame I insert a data to mysql and when it closes I want it to update automatically. I already tried with a windows close event but it does not. Here I leave my code:

//este método lo uso para llenar el combo con una consulta MySQL
//esta es la clase Alta.java
void llena_combo() {

    try {
        jComboBox1.removeAllItems();
        jComboBox3.removeAllItems();
        jComboBox2.removeAllItems();
        Statement st=cn.createStatement();
        ResultSet rs=st.executeQuery("Select * from unidades");
        while(rs.next())
        {                
            jComboBox1.addItem(rs.getString("unidad"));
            jComboBox3.addItem(rs.getString("unidad"));
            jComboBox2.addItem(rs.getString("unidad"));

        }
    } catch (SQLException ex) {
        Logger.getLogger(Alta.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null,ex);
    }     
}

//Ahora en la clase Unidades.java inserto datos y quiero que cuando el usuario cierre la ventana se actualce automaticamente el combo de la clase Alta.java ya lo intente con el evento

private void formWindowClosed(java.awt.event.WindowEvent evt) {                                  
      Alta fr = new Alta();
      fr.llena_combo();
}
//como pueden observar genero un objeto de la clase Alta y ese objeto manda a traer al metodo llena_combo pero no lo hace incluso probe meter el metodo jCombobox.removeAllItems() y si lo hace pero no me explico por que no quiere actualizar mi con el metodo para llenar el combo 
//EL combobox es public static pero no hace nada 
    
asked by Anahi Rosas Trejo 14.09.2016 в 03:02
source

1 answer

2

You must not use multiple JFrame . An application should have only one. You MUST use a JDialog of for daughters windows.

public class Form2 extends JDialog{...}

It is the responsibility of the daughter window to update So when the "Save" button in the dialog box is clicked. The code ActionListener has to do two things:

  • Update the database with the new value
  • Update the combo box with the new value. So this means that when you create the JDialog you need to approve the combo box (or the ComboBoxModel) as a parameter to that class so you can update the combo box. Or, what you need to return a value from the dialog so that when the dialog is closed you can update the combo box.
  • It is recommended to add elements to your combo through a model for example DefaultComboBoxModel

    static DefaultComboBoxModel modelo;//declarar static e instanciarla en tu contructor'
    public Jfram1() {
        initComponents();
        modelo = new DefaultComboBoxModel();
       llena_combo(); // llenar los datos al ejecutar el programa
    }
    

    Your method to fill in a combo could be something like this

    static void llena_combo(){ // static para poder llamarlo desde el otro frame o JDialog
    
    try {
        modelo.removeAllElements(); // eliminamos lo elementos
        Statement st=cn.createStatement();
        ResultSet rs=st.executeQuery("Select * from unidades");
        while(rs.next())
        {                
            modelo.addElement(rs.getString("unidad"));
        }
         combo.setModel(modelo); // seteamos el modelo y se cargan los datos
    } catch (SQLException ex) {
        Logger.getLogger(Alta.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null,ex);
    }     
    

    and the windowClosing event of your second form where you add the data to the database would be

    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
            if (JOptionPane.showConfirmDialog(null, 
                "Está seguro que desea Salir?", "Desea Salir?", 
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
                dispose();
                Jfram1.llenarCombo();
            }
    
        
    answered by 14.09.2016 / 04:33
    source