1
I need my Arraylist data structure to be visible in more than one method of my Products class.
This is how I’m working:
package estoque;
import java.awt.Component;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.util.ArrayList;
public class produtos {
   public static void cadastro() {
      ArrayList<String> Produto = new ArrayList<>();
      JTextField field1 = new JTextField();
      JTextField field2 = new JTextField();
      JTextField field3 = new JTextField();
      Object[] message = {
         "Código:", field1,
         "Descrição:", field2,
         "Quantidade:", field3};
      Component parent = null;
      int option = JOptionPane.showConfirmDialog(parent, message, "Cadastro de Produtos", JOptionPane.OK_CANCEL_OPTION);
      if (option == JOptionPane.OK_OPTION) {
         String codigo = field1.getText();
         String descricao = field2.getText();
         String quantidade = field3.getText();
         if (codigo.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Por favor, preencha o campo Código!");
            cadastro();
         } else if (descricao.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Por favor, preencha o campo Descrição!");
            cadastro();
         } else if (quantidade.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Por favor, preencha o campo Quantidade!");
            cadastro();
         } else {
            Produto.add(codigo + ' ' + descricao + ' ' + quantidade);
            JOptionPane.showMessageDialog(null, "Produto cadastrado com sucesso!");
            System.out.println(Produto);
            Estoque.menu();
         }
      }
   }
   public static void listar() {
      JOptionPane.showMessageDialog(null, " Código - Descrição - Produto\n", "Lista de Produtos", 1);
   }
}
From the menu I access Registration and I register a product that will be stored in  ArrayList<String> Produto = new ArrayList<>();
Then I go back to another class called Menu and select the List Option, which accesses the list method();
In this method the Arraylist is not global, therefore I cannot access it, as I can make it global to perform the reading in this method ?
Place it as a class attribute:
private ArrayList<String> Produto = new ArrayList<>();– user28595
Then the Product Arraylist is not visible in the method, as I would call it ?
– Gabriel Rodrigues
Now that I’ve noticed it’s static. Just add it like this:
private static ArrayList<String> Produto = new ArrayList<>();thus becomes a static class parameter, not an instance parameter.– user28595
That’s what it was! puts as an answer and adds an explanation, so that I can mark it as correct, I had forgotten Static, kind of got a confusion in java when it comes to this!
– Gabriel Rodrigues
I believe this question will not be useful to anyone since my problem was just a flaw in semantics in forgetting the use of Static
– Gabriel Rodrigues
Behold this question.
– Jéf Bueno