Dificuldade em passagem por referência de uma lista

4 respostas
M

Olá, boa noite, senhores. Por favor, gostaria da vossa ajuda com relação a um trabalho da faculdade. destacando que sou iniciante, imagino que essa deve ser uma dúvida bem boba…

o que acontece é a seguinte situação (espero explicar direitinho; de qqer forma, se ficar alguma duvida, posso explicar de novo, postar codigo, sei la)

tenho um jframe chamado “Inicio”, e nesse jframe eu criei uma LinkedList chamada “lista”. agora imaginem que essa lista ja esta preenchida, o usuario ja digitou dados, e tal. tenho tb um jpanel chamado “Painel”, e preciso agora passar aquela lista do frame para esse jpanel… mas acho que preciso passar por referencia, pq, no painel, vou alterar essa lista, e quando for utilizar de novo no jframe inicial, vou precisar dela com as alteraçoes que ela sofreu no jpanel…

alguem pode me ajudar, por favor? se for possivel colocar só um pedacinho de código com a chamada ao jpanel que eu devo fazer no jframe, ficaria muito agradecido.

obrigado

Murilo Marchiori

4 Respostas

S

Olá.

a sua duvida é meio vaga visto que não há codigo.

mas veja se isso ajuda.

code JFrame main:

import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.util.LinkedList;

import javax.swing.JPanel;
import javax.swing.JFrame;

public class InicioView extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private LinkedList<String> lista = new LinkedList<String>();
	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				InicioView thisClass = new InicioView();
				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				thisClass.setVisible(true);
			}
		});
	}

	/**
	 * This is the default constructor
	 */
	public InicioView() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(300, 200);
		this.setContentPane(getJContentPane());
		this.setTitle("JFrame");
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
		}
		return jContentPane;
	}

	private void instanciaPanel(){
		PainelView pv = new PainelView(lista);
		//Agora faca o que tiver de fazer com referencia pv que um objeto de JPanel 
	}
}

code para JPanel

import java.awt.GridBagLayout;
import java.util.LinkedList;

import javax.swing.JPanel;

public class PainelView extends JPanel {

	private static final long serialVersionUID = 1L;

	/**
	 * This is the default constructor
	 */
	public PainelView() {
		super();
		initialize();
	}

	public PainelView(LinkedList<String> lista) {
		super();
		initialize();
	}
	
	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(300, 200);
		this.setLayout(new GridBagLayout());
	}

}

At+

Jailes

M

desculpem a falta de código, mas agora segue: estou postando abaixo duas classes, a classe Inicio e a classe CadastraConta (trata-se de um software para gerenciamento bancário).
A classe Início possui um LinkedList chamado “valores” e tem tb um botao que, ao ser pressionado, chama a classe CadastraConta, e passa “valores” para essa classe. O que eu quero é poder modificar “valores” na classe CadastraConta, e depois poder utilizar novamente “valores” em Inicio, mas já com as modificações que este sofreu em CadastraConta. Acredito que seria uma passagem por referencia, certo?
enfim, segue o codigo:

PS: como é um pouco grande, comentei as partes importantes para a minha dúvida. podem ignorar o restante do código.

Classe Inicio:

package programa_semestre;

import java.util.LinkedList;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

public class Inicio extends javax.swing.JFrame {

    //Como eu havia dito, essa é a lista "valores". Vou precisar, depois, passá-la por referencia
    LinkedList<Cliente> valores = new LinkedList<Cliente>();
    
    public Inicio() {

        initComponents();
    }

    @SuppressWarnings("unchecked")
                              
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btCriaConta = new javax.swing.JButton();
        btAcessoFuncionario = new javax.swing.JButton();
        btAcessoCliente = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        txLogin = new javax.swing.JTextField();
        passwdSenha = new javax.swing.JPasswordField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txLoginFuncionario = new javax.swing.JTextField();
        jSeparator2 = new javax.swing.JSeparator();
        passwdRestrito = new javax.swing.JPasswordField();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        mnuSair = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        mnuSobreBanco = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        mnuSobreSistema = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Boas Vindas");
        setResizable(false);

        jLabel1.setIcon(new javax.swing.ImageIcon("/home/marchiori/Documentos/Faculdade/faculdade_2011/poo/programa_semestre/programa_semestre/images/logo_banco.png"));

        jLabel2.setText("Bem Vindo! Digite seu login e senha");

        btCriaConta.setText("Criar conta");
        btCriaConta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCriaContaActionPerformed(evt);
            }
        });

        btAcessoFuncionario.setText("Acesso Restrito");

        btAcessoCliente.setText("Acessar");
        btAcessoCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAcessoClienteActionPerformed(evt);
            }
        });

        jLabel3.setText("Não possui conta ainda? Crie já a sua!");

        jLabel4.setText("Login");

        jLabel5.setText("Senha");

        jLabel6.setText("Login");

        jLabel7.setText("Senha");

        jMenu1.setText("Opções");
        jMenu1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu1ActionPerformed(evt);
            }
        });

        mnuSair.setText("Sair");
        mnuSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuSairActionPerformed(evt);
            }
        });
        jMenu1.add(mnuSair);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Sobre");
        jMenu2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu2ActionPerformed(evt);
            }
        });

        mnuSobreBanco.setText("Sobre Java's Bank");
        mnuSobreBanco.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuSobreBancoActionPerformed(evt);
            }
        });
        jMenu2.add(mnuSobreBanco);
        jMenu2.add(jSeparator1);

        mnuSobreSistema.setText("Sobre o sistema");
        mnuSobreSistema.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuSobreSistemaActionPerformed(evt);
            }
        });
        jMenu2.add(mnuSobreSistema);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        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(142, 142, 142)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(passwdSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(144, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(197, 197, 197)
                .addComponent(btAcessoCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(197, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(130, 130, 130)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addGap(128, 128, 128))
            .addGroup(layout.createSequentialGroup()
                .addGap(58, 58, 58)
                .addComponent(jLabel1)
                .addContainerGap(58, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 492, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(198, 198, 198)
                .addComponent(btCriaConta)
                .addContainerGap(198, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txLoginFuncionario, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel7)
                .addGap(9, 9, 9)
                .addComponent(passwdRestrito, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btAcessoFuncionario)
                .addContainerGap(43, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btAcessoFuncionario, btCriaConta});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jLabel2)
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(passwdSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btAcessoCliente)
                .addGap(46, 46, 46)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btCriaConta)
                .addGap(18, 18, 18)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btAcessoFuncionario)
                    .addComponent(jLabel7)
                    .addComponent(txLoginFuncionario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(passwdRestrito, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btAcessoCliente, btAcessoFuncionario, btCriaConta});

        pack();
    }

    private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        
    }                                      

    private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        
    }                                      

    private void mnuSobreSistemaActionPerformed(java.awt.event.ActionEvent evt) {                                                
        JOptionPane.showMessageDialog(rootPane, "Informações sobre o software:"
                + "\n\nGerenciador Bancário feito em Java"
                + "\nDesenvolvido por Murilo Marchiori - Ciência da Computação Barão de Mauá 2011"
                + "\nProfessor: Lucas B. Figueira - POO");
    }                                               

    private void mnuSairActionPerformed(java.awt.event.ActionEvent evt) {                                        
        System.exit(0);
    }                                       

    private void mnuSobreBancoActionPerformed(java.awt.event.ActionEvent evt) {                                              
        JOptionPane.showMessageDialog(rootPane, "Informações sobre o Java's Bank:"
                + "\n\nCom tradição no mundo dos negócios, nosso banco completou,"
                + "\nem 2011, 100 anos de existência, contando com a fidelidade e"
                + "\nconfiança de nossos clientes espalhados por todo o globo.");
    }                                             

    private void btCriaContaActionPerformed(java.awt.event.ActionEvent evt) {
                                            
        //Aqui estou chamando a classe CadastraConta, passando valores como referencia. Vou precisar modificar "valores" nessa classe CadastraConta
        CadastraConta cria_conta = new CadastraConta(valores);
        cria_conta.setLocation(350, 190);
        cria_conta.setVisible(true);
        
    }                                           

    private void btAcessoClienteActionPerformed(java.awt.event.ActionEvent evt) {                                                
        
    }                                               

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Inicio().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btAcessoCliente;
    private javax.swing.JButton btAcessoFuncionario;
    private javax.swing.JButton btCriaConta;
    private javax.swing.JLabel jLabel1;
    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.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JMenuItem mnuSair;
    private javax.swing.JMenuItem mnuSobreBanco;
    private javax.swing.JMenuItem mnuSobreSistema;
    private javax.swing.JPasswordField passwdRestrito;
    private javax.swing.JPasswordField passwdSenha;
    private javax.swing.JTextField txLogin;
    private javax.swing.JTextField txLoginFuncionario;
    // End of variables declaration                   

}

Classe CadastraDados

package programa_semestre;

import java.util.LinkedList;
import javax.swing.JOptionPane;

public class CadastraConta extends javax.swing.JDialog {

    public CadastraConta(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    
    //Aqui é onde tento criar o contrutor pegando "valores" do método anterior (Inicio).
    public CadastraConta(LinkedList<Cliente> valores) {
       initComponents();
    }    

    @SuppressWarnings("unchecked")
    
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txNome = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txCpf = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txRua = new javax.swing.JTextField();
        txNumero = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txTelefone = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setModal(true);
        setResizable(false);

        jLabel1.setIcon(new javax.swing.ImageIcon("/home/marchiori/Documentos/Faculdade/faculdade_2011/poo/programa_semestre/programa_semestre/images/logo_banco.png")); 

        jLabel2.setText("Abertura de Conta");

        jLabel3.setText("Nome:");

        jLabel4.setText("CPF");

        jLabel5.setText("Endereço");

        jLabel6.setText("Número");

        jLabel7.setText("Telefone");

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

        jButton2.setText("Limpar campos");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Cancelar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        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(195, 195, 195)
                .addComponent(jLabel2)
                .addContainerGap(181, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(50, 50, 50)
                .addComponent(jLabel1)
                .addContainerGap(56, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(203, 203, 203))
                            .addComponent(txNome, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txRua, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel5))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel6)
                                    .addComponent(txNumero, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(6, 6, 6)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txCpf, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE)
                            .addComponent(jLabel4)
                            .addComponent(jLabel7)
                            .addComponent(txTelefone)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(33, 33, 33)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(26, 26, 26))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jButton2, jButton3});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txRua, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addGap(37, 37, 37))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jButton1, jButton2, jButton3});

        pack();
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        txCpf.setText("");
        txNome.setText("");
        txNumero.setText("");
        txRua.setText("");
        txTelefone.setText("");
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        //Aqui é onde faço um teste para ver se estou conseguindo pegar "valores". tento exibir o nome do cliente,
        //por exemplo, mas não está funcionando. no caso, o nome do cliente que está na posição 1 de "valores"
        Cliente teste;
        teste = valores.get(1);
        JOptionPane.showMessageDialog(rootPane, teste.getNome());
                
    }                                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        if(txCpf.getText().isEmpty() || txNome.getText().isEmpty()
           ||txNumero.getText().isEmpty() || txRua.getText().isEmpty()
           || txTelefone.getText().isEmpty()){

           JOptionPane.showMessageDialog(rootPane, "Por favor, digite todos os dados.", "Erro", JOptionPane.ERROR_MESSAGE);
        }
        else{
            Cliente cliente = new Cliente();

            cliente.setCpf(Integer.parseInt(txCpf.getText()));
            cliente.setNumero(Integer.parseInt(txNumero.getText()));
            cliente.setRua(txCpf.getText());
            cliente.setNome(txCpf.getText());
            cliente.setTelefone(Integer.parseInt(txTelefone.getText()));

            clientes.add(cliente);

            JOptionPane.showMessageDialog(rootPane, "Conta Criada com sucesso!", "Conta criada", JOptionPane.INFORMATION_MESSAGE);
            this.dispose();

        }
    }                                        

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                CadastraConta dialog = new CadastraConta(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    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.JTextField txCpf;
    private javax.swing.JTextField txNome;
    private javax.swing.JTextField txNumero;
    private javax.swing.JTextField txRua;
    private javax.swing.JTextField txTelefone;
    // End of variables declaration                   

}

Se alguem puder me ajudar, agradeço muito.
qqer duvida, estou aí pra esclarecer
obrigado

Murilo Marchiori

S

Olá Murilo,

seguinte pelo que vi teu codigo precisa de pequenas correcoes:

Classe CadastraConta:

1 - Crie uma referencia privada ao objeto CadastroConta da Lista de Clientes recebidas na construcao do objeto, essa referencia seria justamente para voce poder manipular a lista no objeto.

private LinkedList<Cliente> valores;

2 - altere o construtor que voce criou para a forma default e acrescente a lista ou entao so acrescente a lista no construtor default.

private LinkedList<Cliente> valores;
    
    public CadastraConta(java.awt.Frame parent, boolean modal, LinkedList<Cliente> valores) {
        super(parent, modal);
        initComponents();
        //aqui voce informa a lista referencia para objeto
        this.valores = valores;
    }

3 - altere a linha 200 para a lista valida (valores)

//clientes.add(cliente);  
valores.add(cliente);

Classe Inicio
1 - altere a cunstrotur na linha 241

CadastraConta cria_conta = new CadastraConta(this, true, valores);

é isso que deu para analisa. teste e observe possiveis erro para encontramos as solucoes

At+

Jailes

M

Funcionou, parceiro, ficou só uma duvida… se vc puder me explicar…

  1. No cadastra conta, na linha 209, tinha um erro… tava assim:
public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                 //tava dando erro nessa linha aqui embaixo, pq o construtor aqui tinha só dois argumentos e agora teria 3, pq eu passava "valores" tb.
                 CadastraConta dialog = new CadastraConta(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

o que eu fiz… simplesmente coloquei “valores” no final, entao aquela linha ficou assim:

CadastraConta dialog = new CadastraConta(new javax.swing.JFrame(), true, valores);

mas aí continuou dando erro, dizia que nao tava dando certo pq eu tava referenciando um elemento não-estático. daí eu fui lá em cima, na declaração da linkedlist, que antes estava

private LinkedList valores;

e coloquei

private static LinkedList valores;

minha dúvida é: posso fazer isso? a colocação desse static no código vai interferir, vai dar algum problema, quando eu for acessar essa linkedlist novamente em Inicio?

Criado 30 de abril de 2011
Ultima resposta 1 de mai. de 2011
Respostas 4
Participantes 2