how to create an arrangement, where data is saved until the program is finished, using different classes in java?

0

I have to do a project of my programming class 1 in which it consists in making a game where there will be a main menu which will have these buttons:

1.create player
2.Start session
3. go away.

Then create jframes for the options to start session, but focus on the jframe "create player" I made a class called player, where I stored all the methods and variables that I used, here is all the code in the class "player":

public class jugador {
    String nombUsuario;//variable que guardara el nombre de usuario
    private String contra;//esta variable guardara la contrasena
    String[] usuarios = new String[ 15 ];//crea un arreglo donde se guardaran todos los nombres de usuario
    String[] contras = new String[ 15 ];//crea un arreglo donde se guardaran todas las contrasenas.


//*****este metodo hace que se agregue un jugador***********
    public boolean agregarJugador(String nombUsuario, String contra){
        int y = 0;
        int x;
        for(x = 0; x <= 14; x++){
            if(usuarios[x] == null){
                y = x;
                break;
      }  
        }
        usuarios[y] = nombUsuario;
        contras[y] = contra; 
        return true;
    }
    public boolean comprobarJugador(String nombUsuarios, String contr){
        for(int n = 0;n <= 14; n++){
            if(nombUsuarios == usuarios[n] && contr == contras[n]){
                return true;
            }
        }
        return false;
    }


}

and now in the class called createPlayer, there I have the textfield to add the username and password to be created and a button called "Create Player" so when I create create player I keep the values written in username and password, but when (without closing the program) I create Player again and add another user name and another password, I do not keep it in the same array that I believe in the player class, and well here is the code that is in the createPlayer class:

    import java.util.Arrays;
    import javax.swing.JOptionPane;

    /**
     *
     * @author damasofc
     */
    public class crearPlayer extends javax.swing.JFrame {
        jugador jug = new jugador();
    /**
     * Creates new form crearPlayer
     */
    public crearPlayer() {
        initComponents();
        setLocationRelativeTo(null);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jtf_usuario = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        bt_crearJugador = new javax.swing.JButton();
        bt_atras = new javax.swing.JButton();
        psw_contra = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
        jLabel1.setText("Nuevo Jugador");

        jLabel2.setText("Usuario");

        jLabel3.setText("Contraseña");

        bt_crearJugador.setText("Crear Jugador");
        bt_crearJugador.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_crearJugadorActionPerformed(evt);
            }
        });

        bt_atras.setText("Atras");
        bt_atras.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_atrasActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 67, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(98, 98, 98))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel2))
                                .addGap(44, 44, 44)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jtf_usuario, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
                                    .addComponent(psw_contra))
                                .addGap(81, 81, 81))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(bt_atras)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
            .addGroup(layout.createSequentialGroup()
                .addGap(125, 125, 125)
                .addComponent(bt_crearJugador)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 52, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtf_usuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(psw_contra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(bt_crearJugador)
                .addGap(65, 65, 65)
                .addComponent(bt_atras)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void bt_crearJugadorActionPerformed(java.awt.event.ActionEvent evt) {                                                
        //creo un objeto de la clase jugador
        // ******** ACA COMPRUEBA QUE SE HAYA AGREGADO EL JUGADOR CON EXITO Y SI ES ASI, MANDA UN MENSAJE DICIENDO: JUGADOR CREADO*****
        if(jug.comprobarJugador(jtf_usuario.getText(), psw_contra.getText()) == true){
            JOptionPane.showMessageDialog(null,"Jugador ya existente","Error",JOptionPane.ERROR_MESSAGE);
        }
        else{
            //JOptionPane.showMessageDialog(null,"Jugador ya existente","Error",JOptionPane.ERROR_MESSAGE);
            if( jug.agregarJugador(jtf_usuario.getText(), psw_contra.getText()) == true){
                JOptionPane.showMessageDialog(null,"Jugador creado","Excelente",JOptionPane.INFORMATION_MESSAGE);
                Menu_inicio pal = new Menu_inicio();//aca creo un objeto de la clase Menu_inicio
                this.setVisible(false);//aca se cierra esta ventana actual de crearPlayer
                pal.setVisible(true);//etso hace que se abra la ventana de Menu_inicio
        }
       }
        System.out.println(Arrays.toString(jug.usuarios));

    }                                               

    private void bt_atrasActionPerformed(java.awt.event.ActionEvent evt) {                                         
        Menu_inicio pal = new Menu_inicio();//aca creo un objeto de la clase Menu_inicio
        pal.setVisible(true);//etso hace que se abra la ventana de Menu_inicio
        this.dispose();//aca se cierra esta ventana actual de crearPlayer
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(crearPlayer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(crearPlayer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(crearPlayer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(crearPlayer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new crearPlayer().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton bt_atras;
    private javax.swing.JButton bt_crearJugador;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField jtf_usuario;
    private javax.swing.JPasswordField psw_contra;
    // End of variables declaration                   
}
    
asked by Damaso Fernandez 08.02.2017 в 17:13
source

1 answer

1

First of all I would recommend you to look more at Java programming. Classes by rule should be created with the first letter capitalized such that: Jugador . Your class should have a constructor, with which to create a Jugador :

public Jugador (String nombre, String contraseña) 
{
    this.nombUsuario = nombre;
    this.contra = contraseña;
}

Your problem is that you can not create the array in the player class, since every time you initialize it with new Jugador(...) you initialize each of the arrays again. The array should have it in a class, or a "main" screen or where the data will be displayed. On the other hand I would use ArrayList since it is more comfortable than array .

Initializing the ArrayList as follows:

ArrayList<Jugador> jugadores = new ArrayList<Jugador>();

And adding them to this list like this:

jugadores.add(new Jugador("Pepito", "1234"));

So your method would be simpler:

public boolean agregarJugador(String nombUsuario, String contra){
    jugadores.add(nombUsuario, contra);
    return true;
}
  

Eye! Your ArrayList , as I said before, you should have it in the   main form (for example) since it is not going to instantiate several   times (or should not) To do this you must use GETTER or put   your ArrayList as public.

I added a link to a tutorial pretty basic about ArrayList and that I could help you.

    
answered by 08.02.2017 / 17:48
source