Pass values from one .java to another .java using a button - JAVA [duplicated]

-1

I would like to move / move the data from archivo1.java to another archivo2.java .

The relationship will be made by clicking on a button called " button_OK ".

How can you pass values from% co_from% file1.java to other% co_from% file2? More specifically, by selecting a row from a table next by pressing the " JFrame " button and send / load the data of the selected row to fields JFrame in button_OK .

File1.java

    private void button_comprarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button_comprarActionPerformed
        int filaseleccionada;
        try{
            //Guardamos en un entero la fila seleccionada.
            filaseleccionada = table_comprados.getSelectedRow();
            if (filaseleccionada == -1){
                JOptionPane.showMessageDialog(null, "No ha seleccionado ninguna fila.");
            } else {
                Comprar_vehiculo cv = new Comprar_vehiculo(null, rootPaneCheckingEnabled);
                cv.setVisible(true);
                pasarDatosFila();
            }
        }catch (HeadlessException ex){
            JOptionPane.showMessageDialog(null, "Error: "+ex+"\nInténtelo nuevamente", " .::Error En la Operacion::." ,JOptionPane.ERROR_MESSAGE);
        }        
    }

    public void pasarDatosFila(){
        int filaseleccionada = table_comprados.getSelectedRow();
        String bastidor = (String)table_comprados.getValueAt(filaseleccionada, 0);
        String color = (String)table_comprados.getValueAt(filaseleccionada, 1);
        String matricula = (String)table_comprados.getValueAt(filaseleccionada, 2);
        String marca = (String)table_comprados.getValueAt(filaseleccionada, 3);

        //Volcamos los datos de la tabla en los jTextFields.
        Object[] vc = new Object[4];
        vc[0] = bastidor;
        vc[1] = color;
        vc[2] = matricula;
        vc[3] = marca;
    }

File2.java

...
...
textfield_campoX.setText(¿cómo obtengo el valor de las funciones de Archivo1.java?);
...
...
    
asked by omaza1990 16.01.2017 в 09:13
source

1 answer

1

Dear omaza1990:

To be able to pass data from one form to another, first there must be communication between them, which can be done in many different ways.

A simple way is to pass the reference of form 2 (to which you want to send the data) to form 1 (the one that sends the data)

This way you can directly execute methods (public and / or obviously accessible) and you can send parameters.

I'll give you the following example with a minimum code:

public class Main {
    public static void main(String[] args) {
        JFrame1 jFrame1 = new JFrame1(); //crear el primer Jframe
        JFrame2 jFrame2 = new JFrame2(); //crear el segundo jframe
        jFrame1.setJframe2(jFrame2);// aqui le paso la referencia del jframe 2 al jframe1
        jFrame1.setVisible(true);
        jFrame2.setVisible(true);
    }
}

must take into account that within Jframe1 have a variable that serves to store Jframe 2, in addition to it within jframe 2 you must have a method (public) that jframe 1 can execute, this method will be the mechanism by which jframe 1 will send data to jframe 2

This is the code of Jframe1 only contains a jtextfield (to write the data) and a button (to send the data to jframe2)

public class JFrame1 extends javax.swing.JFrame {

    /**
     * Creates new form JFrame1
     */
    private JFrame2 jFrame2;//variable de referencia a jframe 2

    public JFrame1() {
        initComponents();
    }
     /**
      * Metodo que sirve para pasar la referencia de jframe 2 a jframe 1
      * @param jFrame2 
      */
    public void setJframe2(JFrame2 jFrame2) {
        this.jFrame2 = jFrame2;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextField1.setText("jTextField1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(173, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(154, 154, 154))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(127, Short.MAX_VALUE)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addGap(112, 112, 112))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        jFrame2.recibirDato(jTextField1.getText());
    }                                        

    /**
     * @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(JFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrame1.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 JFrame1().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}

This is the code of jframe 2 only has a jtextfield in which you will see the data sent by jframe 1

public class JFrame2 extends javax.swing.JFrame {

    /**
     * Creates new form JFrame2
     */
    public JFrame2() {
        initComponents();
    }

    public void recibirDato(String dato){
        jTextField1.setText(dato);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextField1.setText("jTextField1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(166, 166, 166)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(175, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(120, 120, 120)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(160, Short.MAX_VALUE))
        );

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

    /**
     * @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(JFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrame2.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 JFrame2().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}
    
answered by 16.01.2017 / 14:49
source