I cannot assign value to an Object Arraylist

Asked

Viewed 362 times

1

It’s the following guys, in my project I have three different classes, one is a model (Client), one is the main, which has a Client arraylist, and another is a window.

My intention is to register the data typed in the window in the object’s arraylist, but I’m not getting !

Customer (model) class: Normal class, with name, address and telephone getters and setters.

Main class :

package br.projeto.view;

import java.util.ArrayList;
import br.projeto.model.Cliente;

public class Main {

    public static ArrayList <Cliente> clienteDB = new ArrayList<>();

    public static void main(String[] args) {
        //new Principal();
        //new PedidoRapido();
        new Cadastrar();
    }
}

Register Class (part that matters [window]):

btnCadastrar.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                Main.clienteDB.setNome("");
            }
        });

The point is that in this Main.clienteDB.setNome was only placed there to exemplify what I want to do, because I am not able to access any attribute of the Client object. What should I do ?

2 answers

1

Main.clienteDB does not return you Client but Arraylist. To have a customer and be able to do what you want you need to say which customer you want Main.clienteDB.get(0).getNome(). Obviously this will return exception if your list has no record with index 0, or index you want.

0


It seems to me what you want is to insert a new Cliente on the list. Starting from this assumption:

First, create a copy of Cliente and assign the name you want:

Cliente novoCliente = new Cliente();
novoCliente.setNome("Novo cliente");
// setEndereco, setTelefone etc.

Then enter at the bottom of the list:

Main.clienteDB.add(novoCliente);
  • Thanks man! That’s exactly what I wanted, but when I go for example, pick up some Client from this Array, I will type Main.clienteDB.contains(nome do cliente) ?

  • You mean to take the Client object corresponding to the name?

  • Yes ! For example, if Arraylist has the name typed, the program opens a window ... Just take the typed content and play inside a .contains() ?

  • @Danielsantos take a look in that reply. It gives an example of how to do it. If you have questions, feel free to open another question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.