2016-10-05 32 views
-1

我正在寫這個代碼,應該讓我添加一個學生到一個虛構的數據庫,一切工作正常,但setMail字符串不斷重置爲空

如果我從main運行代碼,當到達郵件部分時,在我編寫郵件並選擇郵件服務(@gmail,@hotmail等)之後,我按aceptar,它應該連接用戶名和郵件服務,但相反,它會得到一個空字符串。

如果我只運行JPane它工作正常。我甚至可以從Correos.java獲得setMail(屬於RegistroEstudiante.java)。

但是,如果我從RegistroEstudiante.java運行它,字符串始終爲空。

通過控制檯基本測試:這兩個應該是相同的

Print from Correos.java: [email protected] 
Print from RegistroEstudiante.java: null 

package escuela; 
import javax.swing.Box; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 
import javax.swing.*; 

import org.apache.commons.lang3.StringUtils; 

public class Estudiante { 

public static void main(String[] args) { 
RegistroEstudiante estudiante = new RegistroEstudiante(); 

    estudiante.inicio(); 
} 


} 

package escuela; 
import javax.swing.JOptionPane; 
import org.apache.commons.lang3.StringUtils; 

public class RegistroEstudiante{ 

private int matricula = 0; //Sólo 6 dígitos 
private byte edad = 0; //No menor de 0 
private float altura = 0.0F; 
private String nombre = null, menu = null, ape_paterno = null, ape_materno = null, correo = null, genero = null, estadoCivil; 
private int length = 0; 
private boolean error = false; 

public void inicio() { 
    String[] menuPrincipal = { "Ingresar", "Mostrar", "Salir" }; 
    String[] genero    = { "Masculino", "Femenino" }; 
    String[] estadoCivilMenu = { "Soltero/a", "Comprometido/a", "Casado/a", "Divorciado/a", "Viudo/a" }; 
    Correos Correos = new Correos(); 
    do { 
     try { 
      setMenu((String)JOptionPane.showInputDialog(null, "¿Qué deseas hacer?", "UNACAR", JOptionPane.QUESTION_MESSAGE, null, menuPrincipal, menuPrincipal[0])); 

    switch(getMenu()) { 
    case "Ingresar": 
     do{ 
      setError(false); 
     try { 
      setMatricula(Integer.parseInt((String)JOptionPane.showInputDialog(null, "Introduce Matrícula [6]", "Agregando estudiante", JOptionPane.QUESTION_MESSAGE, null, null, null))); 
     } catch (java.lang.NumberFormatException e) { 
      JOptionPane.showMessageDialog(null, "Introdujiste un caractér inválido", "Error", JOptionPane.ERROR_MESSAGE, null); 
      setError(true); 
     }  
     length = (int)(Math.log10(getMatricula())+1); // Saca cantidad de caracteres 
     if ((length != 6) && (error == false)) 
     { 
      JOptionPane.showMessageDialog(null, "La Matrícula DEBE ser de 6 dígitos", "Error", JOptionPane.ERROR_MESSAGE, null); 
      setMatricula(0); 
     } 
      } while (length != 6); 

     //SET NOMBRE 
     do{ 
      setError(false); 
      setNombre((String)JOptionPane.showInputDialog(null, "Introduce nombre del alumno", "Agregando estudiante", JOptionPane.QUESTION_MESSAGE, null, null, null)); 
      if(StringUtils.isAlpha(getNombre()) == false) 
      { 
       JOptionPane.showMessageDialog(null, "El nombre debe contener únicamente letras [A-Za-z]", "Error", JOptionPane.ERROR_MESSAGE, null); 
       setNombre(null); 
       setError(true); 
      } 

     }while(isError() == true); 

     //SET APELLIDO PATERNO 
     do{ 
      setError(false); 
      setApe_paterno((String)JOptionPane.showInputDialog(null, "Introduce apellido paterno de " + getNombre(), "Agregando estudiante", JOptionPane.QUESTION_MESSAGE, null, null, null)); 
      if(StringUtils.isAlpha(getApe_paterno()) == false) 
      { 
       JOptionPane.showMessageDialog(null, "El apellido debe contener únicamente letras [A-Za-z]", "Error", JOptionPane.ERROR_MESSAGE, null); 
       setApe_paterno(null); 
       setError(true); 
      } 

     }while(isError() == true); 

     //SET APellido MATERNO FTW 

     do{ 
      setError(false); 
      setApe_materno((String)JOptionPane.showInputDialog(null, "Introduce apellido materno de " + getNombre(), "Agregando estudiante", JOptionPane.QUESTION_MESSAGE, null, null, null)); 
      if(StringUtils.isAlpha(getApe_materno()) == false) 
      { 
       JOptionPane.showMessageDialog(null, "El nombre debe contener únicamente letras [A-Za-z]", "Error", JOptionPane.ERROR_MESSAGE, null); 
       setApe_materno(null); 
       setError(true); 
      } 

     }while(isError() == true); 

     // SELECCIONA SEXO 

     if(JOptionPane.showOptionDialog(null, "Selecciona género de " + getNombre(), "Agregando estudiante", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, genero, genero[0]) == 0){ 
      setGenero("Masculino"); 
     }else{ 
       setGenero("Femenino"); 
     } 

     // SET ESTADO CIVIL COMPA 

     setEstadoCivil((String)JOptionPane.showInputDialog(null, "Estado Civil de " + getNombre(), "UNACAR", JOptionPane.QUESTION_MESSAGE, null, estadoCivilMenu, estadoCivilMenu[0])); 

     // SET EDAD 
     do{ 
      setError(false); 
      try { 
       setEdad(Byte.parseByte((String)JOptionPane.showInputDialog(null, "Introduce la edad del alumno", "Agregando estudiante", JOptionPane.QUESTION_MESSAGE, null, null, null))); 
      } catch (java.lang.NumberFormatException e) { 
       JOptionPane.showMessageDialog(null, "Aquí no se aceptan números...", "Error", JOptionPane.ERROR_MESSAGE, null); 
       setError(true); 
      } 
      if(getEdad() < 0) 
      { 
       JOptionPane.showMessageDialog(null, getNombre() + " no puede tener 0 años o menos, corrige... ", "Error", JOptionPane.ERROR_MESSAGE, null); 
       setEdad((byte) 0); 
       setError(true); 
      } 

     }while(isError() == true); 


     //SET ALTURA 

     do{ 
      setError(false); 
      try { 
       setAltura(Float.parseFloat((String)JOptionPane.showInputDialog(null, "Introduce la altura del alumno", "Agregando estudiante", JOptionPane.QUESTION_MESSAGE, null, null, null))); 
      } catch (java.lang.NumberFormatException e) { 
       JOptionPane.showMessageDialog(null, "Aquí no se aceptan letras...", "Error", JOptionPane.ERROR_MESSAGE, null); 
       setError(true); 
      } 

      if(getAltura() < 0) 
      { 
       JOptionPane.showMessageDialog(null, getNombre() + " no puede medir 0 centimetros o menos, corrige...", "Error", JOptionPane.ERROR_MESSAGE, null); 
       setAltura(0.0F); 
       setError(true); 
      } 

     }while(isError() == true); 

     // SetMail 
     escuela.Correos.main(); 

     do { 
      try { 
      // setCorreo(correos.getCorreoConcatenado()); 
       System.out.println("En RegistroEstudiante.java " + correo); 
       Thread.sleep(1000); 

      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } while (correo == null); 
     break; 

    case "Mostrar": 
     break; 


     } // END SWITCH 
    }// END TRY 
    catch (java.lang.NullPointerException e) { 
     switch(JOptionPane.showConfirmDialog(null, "¿Seguro que deseas salir?", "Salir o no salir?.. He ahí la cuestión...", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null)) { 
     case 0: 
      return; 

     case 1: 
      break; 
    } 
    } 
    } while (getMenu() != "Salir"); 

} 

public boolean sonLetras(String name) { 
    return name.matches("[a-zA-Z]+"); 
} 

public int getMatricula() { 
    return matricula; 
} 

public void setMatricula(int matricula) { 
    this.matricula = matricula; 
} 

public byte getEdad() { 
    return edad; 
} 

public void setEdad(byte edad) { 
    if(edad < 0) 
     JOptionPane.showMessageDialog(null, "No se aceptan valores menores a 0", "Error", JOptionPane.WARNING_MESSAGE, null); 
    this.edad = edad; 
} 

public float getAltura() { 
    return altura; 
} 

public void setAltura(float altura) { 
    this.altura = altura; 
} 

public String getNombre() { 
    return nombre; 
} 

public void setNombre(String nombre) { 
    this.nombre = nombre; 
} 

public String getApe_paterno() { 
    return ape_paterno; 
} 

public void setApe_paterno(String ape_paterno) { 
    this.ape_paterno = ape_paterno; 
} 

public String getApe_materno() { 
    return ape_materno; 
} 

public void setApe_materno(String ape_materno) { 
    this.ape_materno = ape_materno; 
} 

public String getCorreo() { 
    return correo; 
} 

public void setCorreo(String correo) { 
    this.correo = correo; 
} 



public int getLength() { 
    return length; 
} 



public void setLength(int length) { 
    this.length = length; 
} 



public boolean isError() { 
    return error; 
} 



public void setError(boolean error) { 
    this.error = error; 
} 


public String getGenero() { 
    return genero; 
} 


public void setGenero(String genero) { 
    this.genero = genero; 
} 


public String getEstadoCivil() { 
    return estadoCivil; 
} 


public void setEstadoCivil(String estadoCivil) { 
    this.estadoCivil = estadoCivil; 
} 

public String getMenu() { 
    return menu; 
} 

public void setMenu(String menu) { 
    this.menu = menu; 
} 

} 

package escuela; 

import java.awt.Component; 
import java.awt.EventQueue; 
import java.awt.Font; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 

import javax.swing.DefaultComboBoxModel; 
import javax.swing.JButton; 
import javax.swing.JComboBox; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPopupMenu; 
import javax.swing.JTextField; 

import org.eclipse.wb.swing.FocusTraversalOnArray; 
import java.awt.Window.Type; 

public class Correos { 

private JFrame frmAgregandoEstudiante; 
private JTextField txtUsuario; 
private String correoConcatenado = null; 

/** 
* Launch the application. 
*/ 
public static void main() { 
    EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      try { 
       Correos window = new Correos(); 
       window.frmAgregandoEstudiante.setVisible(true); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

/** 
* Create the application. 
*/ 
public Correos() { 
    initialize(); 
} 

/** 
* Initialize the contents of the frame. 
*/ 
private void initialize() { 
    frmAgregandoEstudiante = new JFrame(); 
    frmAgregandoEstudiante.setAlwaysOnTop(true); 
    frmAgregandoEstudiante.setResizable(false); 
    frmAgregandoEstudiante.setTitle("Agregando estudiante"); 
    frmAgregandoEstudiante.setBounds(100, 100, 272, 164); 
    frmAgregandoEstudiante.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frmAgregandoEstudiante.getContentPane().setLayout(null); 

    txtUsuario = new JTextField(); 
    txtUsuario.setToolTipText("Introduce la primera parte de tu correo"); 
    txtUsuario.setBounds(10, 48, 104, 30); 
    frmAgregandoEstudiante.getContentPane().add(txtUsuario); 
    txtUsuario.setColumns(10); 

    JComboBox comboBox = new JComboBox(); 
    comboBox.setModel(new DefaultComboBoxModel(new String[] {"@gmail.com", "@outlook.com", "@unacar.mx", "@live.com", "@yahoo.com", "@hotmail.com"})); 
    comboBox.setBounds(124, 48, 119, 30); 
    frmAgregandoEstudiante.getContentPane().add(comboBox); 

    JButton btnAgregar = new JButton("Agregar"); 
    btnAgregar.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent arg0) { 
      String user,mail; 
      RegistroEstudiante re = new RegistroEstudiante(); 

      user = txtUsuario.getText(); 
      mail = (String) comboBox.getSelectedItem(); 
      setCorreoConcatenado(user.concat(mail)); 
      re.setCorreo(getCorreoConcatenado()); 
      System.out.println("re.setcorreo " + re.getCorreo()); 


     } 
    }); 
    btnAgregar.setBounds(77, 89, 89, 23); 
    frmAgregandoEstudiante.getContentPane().add(btnAgregar); 

    JLabel lblNewLabel = new JLabel("Agrega el correo del estudiante"); 
    lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 14)); 
    lblNewLabel.setBounds(10, 11, 207, 27); 
    frmAgregandoEstudiante.getContentPane().add(lblNewLabel); 
    frmAgregandoEstudiante.getContentPane().setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{txtUsuario, comboBox, btnAgregar})); 
} 
private static void addPopup(Component component, final JPopupMenu popup) { 
    component.addMouseListener(new MouseAdapter() { 
     public void mousePressed(MouseEvent e) { 
      if (e.isPopupTrigger()) { 
       showMenu(e); 
      } 
     } 
     public void mouseReleased(MouseEvent e) { 
      if (e.isPopupTrigger()) { 
       showMenu(e); 
      } 
     } 
     private void showMenu(MouseEvent e) { 
      popup.show(e.getComponent(), e.getX(), e.getY()); 
     } 
    }); 
} 

public String getCorreoConcatenado() { 
    return correoConcatenado; 
} 

public void setCorreoConcatenado(String correoConcatenado) { 
    this.correoConcatenado = correoConcatenado; 
} 
} 
+0

你初始化字符串郵報? –

+0

@RishabhKumar是的,它是initializedprivate String nombre = null,menu = null,ape_paterno = null,ape_materno = null,correo = null,genero = null,estadoCivil; –

回答

1

從Correos.java調用RegistroEstudiante.setCorreo()似乎發生在不同於do-while循環(main)的線程(AWT)上,因此correo字段沒有得到更新。對於某些Thread.currentThread()調用添加到您的代碼,日誌打印輸出以下

En RegistroEstudiante.java null Thread[main,5,main] //Thread.currentThread() printouts from do-while loop 
En RegistroEstudiante.java null Thread[main,5,main] 
setcorreo called: [email protected] Thread[AWT-EventQueue-0,6,main] //Thread.currentThread() printout from setCorreo() 
re.setcorreo [email protected] 
En RegistroEstudiante.java null Thread[main,5,main] 
En RegistroEstudiante.java null Thread[main,5,main] 
+0

感謝您回覆@hammerfest!但正如你可以在日誌打印輸出中看到的那樣,問題沒有解決,點擊'Aceptar'按鈕後,你會看到setcorreo叫做:[email protected]和re.setcorreo:[email protected],但是下一個也應該是[email protected],在RegistroEstudiante.java中,情況並非如此,它會得到一個空字符串。 –

+0

我從來沒有說過它固定任何東西;這些是額外的日誌打印輸出,可以說明問題所在。爲了解決這個問題,我建議你首先考慮對整個代碼進行一般的重構/重組;因爲目前它是一個很難監督的混亂,很可能沒有人會爲你調試和糾正它 – hammerfest

+0

我現在明白你的觀點,@hammerfest!感謝您的信息,我會研究它 –