Pass value of variable INT to another class in Java

-1

I'm using Eclipse and JFrame to create a program. I need to pass the value of a variable type INT from one class to another, but when I try to do it, the value of the variable within the frame of the second class is 0 .

class Father:

public class PAdre extends JFrame {

    /**
     * Global
     */
    private int id_pelicula = 2;

    /**
     * Create the frame.
     */
    public Padre() {
        setTitle("Clase Padre");
        setBounds(100, 100, 628, 410);
        JPanel contentPane = new JPanel();
        setContentPane(contentPane);

        btnVerReferencias = new JButton("Ver Ref.");
        btnVerReferencias.setEnabled(false);
        btnVerReferencias.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                claseHijo classHijo = new claseHijo ();
        // Paso el valor de la variable
                classHijo.setIdPelicula(id_pelicula);
                classHijo.setVisible(true);
            }
        });
        btnVerReferencias.setBounds(12, 288, 110, 74);
        contentPane.add(btnVerReferencias);

    }
}

class Son:

public class classHijo extends JFrame {

    /**
     * Global
     */
    private int id_pelicula;

  // Recibo el valor de la variable
    public void setIdPelicula(int id_pelicula) {
        this.id_pelicula = id_pelicula;
        }

    /**
     * Create the frame.
     */
    public classHijo () {
        setTitle("Clase Hijo");
        setBounds(100, 100, 628, 410);
        JPanel contentPane = new JPanel();
        setContentPane(contentPane);    

    // Le asigno el valor de la variable global
        int otraVariableINT = id_pelicula;
        System.out.println("otraVariableINT : " + otraVariableINT);
    }
}

Exit:

otraVariableINT: 0

Why is the variable id_pelicula worth 0 within frame of the class Son? It is assumed that this variable is global and maintains its value throughout the execution of the program no?.

What is the correct way to pass a value to another class and that is available to use within frame , what do I do wrong?

    
asked by Robert Gomez 13.11.2017 в 14:25
source

3 answers

2

You're making the same mistake last time. Remember that the constructor is the first method to be called from a object . That's something obvious because when you declare the instance of a class, what you're doing is calling the constructor.

claseHijo classHijo = new claseHijo ();

new claseHijo() is the instance of the object, which is also the constructor of the class claseHijo . Keep that in mind, when you create an instance, you're calling the builder of that class.

Now, if you look closely, in the constructor you are printing the value of the variable id_pelicula ; which is zero (zero is the default value of the variables of type int ) because the variable id_pelicula you pass the value when you call the method setIdPelicula() , which is executed after the constructor. Maybe you ask me Can you call that method before the constructor? No, there is no way, the constructor is always the first method that is called of an object.

Knowing this, there are two solutions:

  • Do what you're going to do with the variable id_pelicula (either print it, assign it to another variable ... whatever) within the setIdPelicula() method.

    public void setIdPelicula(int id_pelicula) {
    
        this.id_pelicula = id_pelicula;
    
        // Le asigno el valor de la variable global
        int otraVariableINT = id_pelicula;
    
        System.out.println("otraVariableINT : " + otraVariableINT);
    
    }
    
  • Pass the value of the variable id_pelicula in the class constructor.

    public classHijo (int id_pelicula) {
    
        this.id_pelicula = id_pelicula;
    
        setTitle("Clase Hijo");
        setBounds(100, 100, 628, 410); 
        JPanel contentPane = new JPanel();   
        setContentPane(contentPane); 
    
        // Le asigno el valor de la variable global 
        int otraVariableINT = id_pelicula;
        System.out.println("otraVariableINT : " + otraVariableINT); 
    }
    
  • Other corrections

    The names of the classes have to start with a capital letter. It is not only by convention, that helps to differentiate the classes of the objects and the variables.

    classHijo ❌
    ClassHijo ✅

        
    answered by 15.11.2017 / 00:41
    source
    1

    It seems that your global variable movie_id in your class Vista_verReferenciasPeliculas is initialized to 0 and as I see your prints in the stacktrace the first thing you do in the flow of your application is to call the updateReferences () method and then set the value to movie_id . That's why you're trying to get a value that is not set in your global variable, in fact you even try to get the value before it executes the method of the parent class that sends the value.

    EDITED

    Observing your classes, I realize that you are not clear about how to make the flow of an application, first of all your application does not have to have several starting points, that is, you only have to have a single main in the whole project and not a main for each class. What is the class that you run to start the application?

    Now your method updateReferences (int movie_id) of the class   Vista_verReferenciasPeliculas As I mentioned, it's the first one called. However, this is being called after the updateReferences (movie_id)

    method

    The big problem is that you are calling the updateReferences (movie_id) method from the constructor of the same class and the worst thing is that you are reading a global variable movie_id and it is lé passes as a parameter to the method updateReferences (movie_id) which does not make any sense since the variable is global

    I'll give you the example, you have the global variable movie_id as it is not initialized it takes as value 0 then when your class runs you should know that the first thing that is executed is the constructor. which passes the 0 of the variable movie_id when calling the method updateReferences (movie_id) but you do not need to pass it since it is global.

    The truth could continue all day giving you to know all the errors or bad practices that you do at the time of programming but that is not the goal.

    So first of all correct your entire application by leaving only one main, if the flow starts with the class View_film you can set the variable movie_id by passing the parameter by constructor instead of by method.

                Vista_verReferenciasPeliculas vistaVerReferenciasPeliculas = new Vista_verReferenciasPeliculas(id_pelicula);
    

    and in your class Vista_verReferenciasPeliculas declare that your constructor receives an argument, sets it and does not pass the parameter when calling UpdateReferences because it is global and the method has access to the

       public Vista_verReferenciasPeliculas(id_pelicula){
          this.id_pelicula = id_pelicula;
          ...
          ...
          actualizarReferencias();
        }
    

    That will solve the problem for which you opened the subject although it really is not a problem, since it is not necessary to call vistaVerReferenciasPeliculas.setIdPelicula (id_pelicula)

    And finally if you want to improve, investigate the DTO pattern because it is a bad practice to have global variables, that if you are using multithreading I do not know why you do not know how to use this pattern.

    EDITION 2

    The truth is that I have not used java swing libraries for many years, but I am completely sure that you do not need a main by class or by frame if all you want is for all your windows to load when you run your main class Vista_pelicula The only thing you have to do is create the instance towards all the frames you need to upload and put them as visible

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Vista_pelicula frame = new Vista_pelicula();
                    frame.setVisible(true);
    
                   //Desde aquí llama a todos tus frames que necesites
                       Vista_verReferenciasPeliculas frame = new 
                                Vista_verReferenciasPeliculas();
                    frame.setVisible(true);
    
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    

    But if you still want to keep all your main and your code as it is you will need to use 2 design patterns, one DTO and one singleton.

        
    answered by 13.11.2017 в 18:49
    0

    Your variable movie_id of class Vista_verReferences_Pages is 0 because you did not initialize it with any value, as is a primitive int the default value it's 0 .

    However, I think the confusion here comes because you should think that as in the class Movie_view the attribute movie_id you assigned a value of 2 so in the class > Vista_verReferenciasPeliculas which also has an attribute with the same name should also have that value assigned, which is not the case.

    Please note:

    You decided to extend the two classes of JFrame so the Class Vista_verReferenciasPeliculas could no longer extend it from Vista_pelicula to inherit the attribute id_pelicula, < strong> and even so, if you extend it the value of the variable will be different between class and class , because in truth although they are called the same they are different variables in different classes that can have different values between parents and children.

    import logicas.Logica_verReferenciasPeliculas;
    
    public class Vista_verReferenciasPeliculas extends JFrame {
    
    /**
     * Global
     */
    private static final long serialVersionUID = 1L;
    private JTable table;
    private int id_pelicula;
    Logica_verReferenciasPeliculas logicaVerReferenciasPeliculas  = new Logica_verReferenciasPeliculas();
    
     // Recibo el valor de la variable
    public void setIdPelicula(int id_pelicula) {
    
    //Creas un objeto Vista_pelicula para poder acceder a su atributo id_pelicula.
        Vista_pelicula v = new Vista_pelicula();
    
    //Le asignas al id_pelicula de esta clase el id_pelicula que viene de la clase Vita_pelicula. Tecnicamente deberia funcionar. este método getId_pelicula() lo inventé asumo que como tenés privado el atributo seguramente lo tengas declarado no se si asi pero bueno.
        this.id_pelicula = v.getId_pelicula();
        }
    
    // Recibo el INT como parámetro
    void actualizarReferencias(int id_pelicula) {
        try {
            DefaultTableModel model = logicaVerReferenciasPeliculas.tableReferencias(id_pelicula); // Uso el INT
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Exception:\n" + e, "Error: actualizarReferencias()", JOptionPane.ERROR_MESSAGE);
            }
    }
    
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Vista_verReferenciasPeliculas frame = new Vista_verReferenciasPeliculas();
                    frame.setVisible(true);
                    frame.setLocationRelativeTo(null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    
    /**
     * Create the frame.
     */
    public Vista_verReferenciasPeliculas() {
        setTitle("Referencias");
        setResizable(false);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 628, 410);
        JPanel contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
    
    // Llamo a la función y le paso como argumento un número INT
        actualizarReferencias(id_pelicula);
    }
    }
    
        
    answered by 13.11.2017 в 23:44