java - 仅当方法位于同一类中时才存储值

标签 java swing class null jpanel

我有这段代码,就像一个迷你学校管理系统,在 RegistroEstudiante.java 中,我调用存储在 Operaciones.java 中的方法 它是完美的,直到我选择“Mostar Datos”(显示数据),并且我发现一切都为空除了邮件部分,该方法位于 RegistroEstudiante.java 中

我的意思是,为什么会发生这种情况?我正确使用了 getter 和 setter,我什至在测试代码时打印这些值只是为了看看数字是否正确,但是一旦我代码返回到 RegistroEstudiante.java 并运行显示数据,除了邮件之外的所有内容都被清空。

摘要:

RegistroEstudiante.java:这里有变量、getter 和 setter,还调用位于 Operaciones.java 上的每个函数

Operaciones.java:用于获取数据的每个方法(ID、姓名、姓氏、年龄、高度、邮件、性别等)

过去,所有内容都在同一个类中,并且它有效,我想清理一些代码,现在正在发生这种情况。

<小时/>

RegistroEstudiante.java

    import java.awt.Component;
    import java.awt.EventQueue;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Scanner;

    import javax.swing.DefaultComboBoxModel;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;

    import org.apache.commons.lang3.StringUtils;
    import org.eclipse.wb.swing.FocusTraversalOnArray;


    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, genero = null, estadoCivil = null;
     private int length = 0;
     private boolean error = false;
     //FORMS
     private JFrame frmAgregandoEstudiante;
     private JTextField txtUsuario;
     private String correoConcatenado = null;

     ImageIcon iconoEscuela = new     ImageIcon(RegistroEstudiante.class.getResource("school.png"));
 ImageIcon iconoGender = new ImageIcon(RegistroEstudiante.class.getResource("gender.png"));
 ImageIcon iconoMatricula = new ImageIcon(RegistroEstudiante.class.getResource("password.png"));
 ImageIcon iconoNombre = new ImageIcon(RegistroEstudiante.class.getResource("idcard.png"));
 ImageIcon iconoAltura = new ImageIcon(RegistroEstudiante.class.getResource("ruler.png"));
 ImageIcon iconoEstadoCivil = new ImageIcon(RegistroEstudiante.class.getResource("wedding-rings.png"));
 ImageIcon iconoError = new ImageIcon(RegistroEstudiante.class.getResource("warning.png"));
 ImageIcon iconoEdad = new ImageIcon(RegistroEstudiante.class.getResource("age.png"));
 ImageIcon iconoAdios = new ImageIcon(RegistroEstudiante.class.getResource("wave.png"));

 public class List {
     public int matricula = 0;
     public byte edad = 0;
     public float altura = 0.0F;
     public String nombre = null, ape_paterno = null, ape_materno = null, genero = null, estadoCivil = null;
 }
 public void inicio() {
  String[] menuPrincipal = {
   "Ingresar",
   "Mostrar",
   "Salir"
  };


  Operaciones operacion = new Operaciones();
  do {
   try {
    setMenu((String) JOptionPane.showInputDialog(null, "¿Qué deseas hacer?", "UNACAR", JOptionPane.QUESTION_MESSAGE, iconoEscuela, menuPrincipal, menuPrincipal[0]));
    switch (getMenu()) {
     case "Ingresar":
         operacion.matricula();
      //SET NOMBRE
         operacion.nombre();
      //SET APELLIDO PATERNO
         operacion.ape_paterno();
      //SET APellido MATERNO FTW
         operacion.ape_materno();
      // SELECCIONA SEXOOOOOOOOOOOOOOOO
         operacion.genero();
      // SET ESTADO CIVIL COMPA
         operacion.estadoCivil();
      // SET EDAD
         operacion.edad();
      //SET ALTURA
         operacion.altura();
      // SET CORREOOOO, SO HARD
         setCorreoConcatenado(null);
         inicioCorreos();
         do {
             try {
                 Thread.sleep(500);
             } catch (InterruptedException e) {
        // DOES NOTHING IN HEEEEEERE
             }
         } while (getCorreoConcatenado() == null);
         break;

      // TERMINA INGRESO DE ESTUDIANTE
     case "Mostrar":
         mostrarDatos();
         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, iconoAdios)) {
        case 0:
            return;
        case 1:
            break;
        }
    }

  } while (getMenu() != "Salir");
 }
 public void mostrarDatos() {
      ImageIcon iconoDatos = new ImageIcon(RegistroEstudiante.class.getResource("datos.png"));
      JOptionPane.showMessageDialog(null, "Matrícula: " + getMatricula() + "\nNombre: " + getNombre() + " " + getApe_paterno() + " " + getApe_materno() + "\nGénero:  " + getGenero() + "\nEstado Civil: " + getEstadoCivil() + "\nEdad: " + getEdad() + "\nAltura: " + getAltura() + "\nCorreo: " + getCorreoConcatenado(), "Información Estudiante  " + getNombre(), JOptionPane.INFORMATION_MESSAGE, iconoDatos);
     }
 public void inicioCorreos() {
   EventQueue.invokeLater(new Runnable() {
    public void run() {
     try {
      frmAgregandoEstudiante.setVisible(true);
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
   });
  }
  /**
   * Create the application.
   */
 public RegistroEstudiante() {
   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.setLocationRelativeTo(null);
  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;
    user = (String) txtUsuario.getText();
    mail = (String) comboBox.getSelectedItem();
    setCorreoConcatenado((String) user.concat(mail));
    frmAgregandoEstudiante.dispose();
    txtUsuario.setText(null); //Limpia el correo anterior para que no vuelva a salir
   }
  });
  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
  }));
 }
 public String getCorreoConcatenado() {
  return correoConcatenado;
 }
 public void setCorreoConcatenado(String correoConcatenado) {
  this.correoConcatenado = correoConcatenado;
 }
 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 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;
     }
    }
<小时/>

Operaciones.java

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import org.apache.commons.lang3.StringUtils;



public class Operaciones {
RegistroEstudiante re = new RegistroEstudiante();
  String[] genero = {
           "Masculino",
           "Femenino"
          };
          String[] estadoCivilMenu = {
           "Soltero/a",
           "Comprometido/a",
           "Casado/a",
           "Divorciado/a",
           "Viudo/a"
          };

public void matricula(){
      do {
          re.setError(false);
          try {
           re.setMatricula((Integer.parseInt((String) JOptionPane.showInputDialog(null, "Introduce Matrícula [6]", "Agregando estudiante", JOptionPane.QUESTION_MESSAGE, re.iconoMatricula, null, null))));
          } catch (java.lang.NumberFormatException e) {
           JOptionPane.showMessageDialog(null, "Introdujiste un caractér inválido", "Error", JOptionPane.ERROR_MESSAGE, re.iconoError);
           re.setError(true);
          }
          re.setLength((int)(Math.log10(re.getMatricula() + 1)));
          System.out.println(re.getMatricula());
          System.out.println(re.getLength());// Saca cantidad de caracteres
          if ((re.getLength() != 5) && (re.isError() == false)) {
           JOptionPane.showMessageDialog(null, "La Matrícula DEBE ser de 6 dígitos", "Error", JOptionPane.ERROR_MESSAGE, re.iconoError);
           re.setMatricula(0);
          }
         } while (re.getLength() != 5); 
}

public void nombre(){
     do {

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

public void ape_paterno(){
     do {
         re.setError(false);
         re.setApe_paterno((String) JOptionPane.showInputDialog(null, "Introduce apellido paterno de " + re.getNombre(), "Agregando estudiante", JOptionPane.QUESTION_MESSAGE, re.iconoNombre, null, null));
           if (StringUtils.isAlpha(re.getApe_paterno()) == false) {
            JOptionPane.showMessageDialog(null, "El apellido debe contener únicamente letras [A-Za-z]", "Error", JOptionPane.ERROR_MESSAGE, re.iconoError);
            re.setApe_paterno(null);
            re.setError(true);
           }
          } while (re.isError() == true);
}

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


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

public void estadoCivil(){
     re.setEstadoCivil((String) JOptionPane.showInputDialog(null, "Estado Civil de " + re.getNombre(), "UNACAR", JOptionPane.QUESTION_MESSAGE, re.iconoEstadoCivil, estadoCivilMenu, estadoCivilMenu[0]));
}

public void edad(){
      do {
          re.setError(false);
          try {
              re.setEdad(Byte.parseByte((String) JOptionPane.showInputDialog(null, "Introduce la edad del alumno", "Agregando estudiante", JOptionPane.QUESTION_MESSAGE, re.iconoEdad, null, null)));
          } catch (java.lang.NumberFormatException e) {
           JOptionPane.showMessageDialog(null, "Aquí sólo se aceptan números...", "Error", JOptionPane.ERROR_MESSAGE, re.iconoError);
           re.setError(true);
          }
          if (((re.getEdad() <= 0) || (re.getEdad() >= 60)) && (re.isError() == false)) {
           JOptionPane.showMessageDialog(null, re.getNombre() + " no puede tener 0 años o menos, ni ser mayor de 60, corrige... ", "Error", JOptionPane.ERROR_MESSAGE, re.iconoError);
           re.setEdad((byte) 0);
           re.setError(true);
          }
         } while (re.isError() == true);
}

public void altura(){
    do {
        re.setError(false);
           try {
               re.setAltura(Float.parseFloat((String) JOptionPane.showInputDialog(null, "Introduce la altura del alumno", "Agregando estudiante", JOptionPane.QUESTION_MESSAGE, re.iconoAltura, null, null)));
           } catch (java.lang.NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "Aquí no se aceptan letras...", "Error", JOptionPane.ERROR_MESSAGE, re.iconoError);
            re.setError(true);
           }
           if (re.getAltura() <= 0 && re.isError() == false) {
            JOptionPane.showMessageDialog(null, re.getNombre() + " no puede medir 0 centimetros o menos, corrige...", "Error", JOptionPane.ERROR_MESSAGE, re.iconoError);
            re.setAltura(0.0F);
            re.setError(true);
           }
          } while (re.isError() == true);
}


}

最佳答案

请对combobox.selectedItem 和其他一些您使用的项目使用“System.out” 认为要确保比值被设定! 我认为你的换位失败了。我的意思是你最后设置了 null

//设置 CORREOOOO,太难了

setCorreoConcatenado(null);

关于java - 仅当方法位于同一类中时才存储值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39928781/

相关文章:

java - 真实的物体而不是在 Canvas 上绘画

java - Gridbag 布局未正确对齐

Javascript 类继承无法正常工作

php - 使用 PHP 类时的 SQL 查询效率

c++ - 设置(属性)类的单个/多个成员的最佳实践

java - Spring Boot permitAll 在 WebSecurityConfigurerAdapter 中不起作用

java - 如何在JAVA中使用Elastic Transcoder?

java - 显示 Unity WebPlayer 内容

java - String 与 StringWriter 处理大字符串

java - JFrame 中的 KeyListener 没有响应