Mutante Mutante - 2 months ago 7
Java Question

Use an arraylist from class A in class B

I need to know how to use an arraylist from a class into another class.
I am using a jFrame, when the user clicks in a button I need to transfer that arraylist to another class (i need to use the data in this class).

What I Have:

Class A (My problem is in the jbuton clicked method):

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package computadorrbc;

import java.util.ArrayList;
import javax.swing.DefaultListModel;

/**
*
* @author Iago Sestrem Ochôa
*/
public class Tela extends javax.swing.JFrame {

/**
* Creates new form Tela
*/
public Tela() {
initComponents();
ArrayList<String> gabinete = new ArrayList<String>();
ArrayList<String> processador = new ArrayList<String>();
ArrayList<String> memoria = new ArrayList<String>();
ArrayList<String> hd = new ArrayList<String>();
ArrayList<String> ssd = new ArrayList<String>();
ArrayList<String> gpu = new ArrayList<String>();
ArrayList<String> teclado = new ArrayList<String>();
ArrayList<String> mouse = new ArrayList<String>();
ArrayList<String> fonte = new ArrayList<String>();
ArrayList<String> refrigeracao = new ArrayList<String>();
ArrayList<String> monitor = new ArrayList<String>();
ArrayList<String> headset = new ArrayList<String>();
ArrayList<String> motherboard = new ArrayList<String>();
gabinete.add("Mid Tower");
gabinete.add("Full Tower");
processador.add("i7 6700K");
processador.add("i7 6700");
processador.add("i5 6600K");
processador.add("i5 6600");
memoria.add("HyperX 8GB 1600");
memoria.add("Vengeance 8GB 1600");
memoria.add("HyperX 8GB 1866");
memoria.add("HyperX 8GB 2133");
hd.add("WD 1TB 7200 RPM");
hd.add("Seagate 1TB 7200 RPM");
hd.add("Seagate 2TB 7200 RPM");
ssd.add("Kingston 120GB");
ssd.add("Sandisk 120GB");
ssd.add("Kingston 240GB");
ssd.add("Sandisk 240GB");
gpu.add("AMD R9 390");
gpu.add("AMD R9 Fury");
gpu.add("AMD R9 390X");
gpu.add("GTX 980 TI");
gpu.add("GTX Titan");
gpu.add("GTX 1080");
gpu.add("GTX 1070");
teclado.add("Razer BlackWidow");
teclado.add("Razer DeathStalker");
teclado.add("Razer Cynosa");
mouse.add("Razer Naga");
mouse.add("Razer Abyssus");
mouse.add("Razer Krait");
mouse.add("Razer Deathadder");
fonte.add("EVGA 1600W");
fonte.add("Corsair 1500W");
fonte.add("Coolermaster 1200W");
fonte.add("SeaSonic 1000W");
fonte.add("Corsair 860W");
fonte.add("SeaSonic 520W");
refrigeracao.add("Água");
refrigeracao.add("Ar");
monitor.add("Benq 27p 144Hz");
monitor.add("Asus 27p 144Hz");
monitor.add("Asus 27p QuadHD");
monitor.add("LG 25p FullHD");
monitor.add("Acer 21,5p FullHD");
headset.add("Razer Kraken");
headset.add("Razer TiaMat");
headset.add("Razer Chiamera");
headset.add("Razer Manowar");
headset.add("Logitech G430");
headset.add("Logitech G933");
headset.add("Logitech G35");
motherboard.add("ATX Maximus VIII");
motherboard.add("ATX ROG STRIX");
motherboard.add("ATX Sabertooth");
motherboard.add("ATX 970 PRO");
motherboard.add("ATX GA 970");
DefaultListModel model0 = new DefaultListModel();
for (String s : gabinete) {
jList1.setModel(model0);
model0.addElement(s);
}
DefaultListModel model1 = new DefaultListModel();
for (String s : processador) {
jList2.setModel(model1);
model1.addElement(s);
}
DefaultListModel model2 = new DefaultListModel();
for (String s : memoria) {
jList3.setModel(model2);
model2.addElement(s);
}
DefaultListModel model3= new DefaultListModel();
for (String s : hd) {
jList4.setModel(model3);
model3.addElement(s);
}
DefaultListModel model4 = new DefaultListModel();
for (String s : ssd) {
jList5.setModel(model4);
model4.addElement(s);
}
DefaultListModel model5 = new DefaultListModel();
for (String s : gpu) {
jList6.setModel(model5);
model5.addElement(s);
}
DefaultListModel model6 = new DefaultListModel();
for (String s : teclado) {
jList7.setModel(model6);
model6.addElement(s);
}
DefaultListModel model7 = new DefaultListModel();
for (String s : mouse) {
jList8.setModel(model7);
model7.addElement(s);
}
DefaultListModel model8 = new DefaultListModel();
for (String s : fonte) {
jList9.setModel(model8);
model8.addElement(s);
}
DefaultListModel model9 = new DefaultListModel();
for (String s : refrigeracao) {
jList10.setModel(model9);
model9.addElement(s);
}
DefaultListModel model10 = new DefaultListModel();
for (String s : monitor) {
jList11.setModel(model10);
model10.addElement(s);
}
DefaultListModel model11 = new DefaultListModel();
for (String s : headset) {
jList12.setModel(model11);
model11.addElement(s);
}
DefaultListModel model12 = new DefaultListModel();
for (String s : motherboard) {
jList13.setModel(model12);
model12.addElement(s);
}
}





private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
ArrayList<String> dados = new ArrayList<String>();
dados.add(jList1.getSelectedValue());
dados.add(jList2.getSelectedValue());
dados.add(jList3.getSelectedValue());
dados.add(jList4.getSelectedValue());
dados.add(jList5.getSelectedValue());
dados.add(jList6.getSelectedValue());
dados.add(jList7.getSelectedValue());
dados.add(jList8.getSelectedValue());
dados.add(jList9.getSelectedValue());
dados.add(jList10.getSelectedValue());
dados.add(jList11.getSelectedValue());
dados.add(jList12.getSelectedValue());
dados.add(jList13.getSelectedValue());
TelaRBC dados_rbc = new TelaRBC(dados);
TelaRBC tela_rbc = new TelaRBC();
tela_rbc.setVisible(true);
dispose();
System.out.print(dados);
}

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

// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JList<String> jList1;
private javax.swing.JList<String> jList10;
private javax.swing.JList<String> jList11;
private javax.swing.JList<String> jList12;
private javax.swing.JList<String> jList13;
private javax.swing.JList<String> jList2;
private javax.swing.JList<String> jList3;
private javax.swing.JList<String> jList4;
private javax.swing.JList<String> jList5;
private javax.swing.JList<String> jList6;
private javax.swing.JList<String> jList7;
private javax.swing.JList<String> jList8;
private javax.swing.JList<String> jList9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane10;
private javax.swing.JScrollPane jScrollPane11;
private javax.swing.JScrollPane jScrollPane12;
private javax.swing.JScrollPane jScrollPane13;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JScrollPane jScrollPane6;
private javax.swing.JScrollPane jScrollPane7;
private javax.swing.JScrollPane jScrollPane8;
private javax.swing.JScrollPane jScrollPane9;
// End of variables declaration
}


So I am trying to use the
dados_rbc
in the class B:

package computadorrbc;


public class TelaRBC extends javax.swing.JFrame {


public TelaRBC() {
initComponents();
DefaultListModel model4 = new DefaultListModel();
for (String s : dados_rbc) {
jList.setModel(model4);
model4.addElement(s);
}

}

public static void main(String args[]) {

java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TelaRBC().setVisible(true);
}
});
}

private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;


But this is not working, someone knows another method to use the data from the arraylist of class B into the class B?

Answer

Two ways to solve this immediately come to mind:

  1. Constructor parameters:
    See Austin D's answer.

  2. Setting from origin (class A) after instantiation (of class B):
    In TelaRBC (B), create a Setter method for the model; and through this method, set the model from class A:

    //CLASS B
    public void setDados(ArrayList<String> dados) {
        DefaultListModel model = new DefaultListModel();
        for (String s : dados) {
            model.addElement(s);
        }
        jList.setModel(model);
    }
    
    //CLASS A
    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      
        ArrayList<String> dados = new ArrayList<String>();
        dados.add(jList1.getSelectedValue());
        //...
        dados.add(jList13.getSelectedValue());
        TelaRBC tela_rbc = new TelaRBC();
    
        tela_rbc.setDados(dados); //<<<<<<<<<< The difference.
    
        tela_rbc.setVisible(true);
        System.out.print(dados);
        dispose();
    }
    

Extra: In class A, you should be using a ActionListener instead of a MouseClicked.

Since you're apparently using the NetBeans GUI editor...

  1. In the code tab, copy the code from the current event (Button1MouseClicked()).
  2. In the visual tab, select jButton1.
  3. On the properties window, go to the Events tab, and delete the current MouseClicked event.
  4. Go to the ActionPerformed event (top), add it, and past the code to it.

At the end, you should have no jButton1MouseClicked() method, and instead have this:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    //... (code that was previously in the 'MouseClicked' method)
}
Comments