Dúvida muito simples, por favor ajudem

2 respostas
T

Boa noite pessoal,
Estou iniciando em java e estou com uma dificuldade a principio tão simples que nem sei como explicar, mas vamos lá.

Estou criando um aplicativo no netbeans com as seguintes classes:

Produto.java
ProdutoProcessa.java
FormProduto.java
FormEdicaoProduto.java

A lógica é a seguinte,
A classe FormProduto.java tem o método main e tem um botão de "Novo" que chama
a classe FormEdicaoProduto.java.

Estou usando serialização para registrar os dados que são somente Código e Nome.

Quando entro com dados nos campos jTextField, faço a inserção sem problemas,
mas como eu quero que o código seja gerado automaticamente, estou marcando
o Jtextfield de codigo como Enable= false.

Minha dúvida é a seguinte, como eu faço para ler o último parametro do objeto serializado no arquivo.txt
e somar +1 quando eu entro no formulário.

Vou tentar ser mais claro, o que eu tenho que fazer para que na hora que o formulario abrir, o campo de código
receber algum valor.

Pessoal, é uma dúvida bem simples, mas estou procurando no Bigjava e na net e ainda não consegui achar nada.

Segue os código das classes:

Produto.java
package aula20080726;

import java.io.Serializable;


public class Produto implements Serializable{
	private int codigo;
	private String nome;

	
	public int getCodigo() {
		return codigo;
	}
	public void setCodigo(int codigo) {
		this.codigo = codigo;
	}
	public String getNome() {
		return nome;
	}
	public void setNome(String nome) {
		this.nome = nome;
	}
}
ProdutoProcessa.java
package aula20080726;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javax.swing.JOptionPane;



public class ProdutoProcessa extends Produto {
    
    public void insere(int cod, String nome){
         Produto p = new Produto();
         p.setCodigo(cod);
         p.setNome(nome);
        
                  
         ArrayList listaLida = null;
         try {
                ObjectOutput out = new ObjectOutputStream(new FileOutputStream("produto1.txt"));
	        out.writeObject(p);
	        out.close();
                
                JOptionPane.showMessageDialog(null, "Produto Incluido com sucesso!");
                                      
            } catch (IOException e) {
            e.printStackTrace();
            }

    }
    
    public void pesquisa() throws ClassNotFoundException{
        Produto p2 = null;
        try {
                File file = new File("produto1.txt");
	        ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
	        p2 = (Produto) in.readObject();
	        in.close();
                
                JOptionPane.showMessageDialog(null, p2.getNome());
                
                       
            } catch (IOException e) {
            e.printStackTrace();
            }
        //return p2.getCodigo();
     }
      
}
FormProduto.java
package aula20080726;

import java.util.logging.Level;
import java.util.logging.Logger;

public class FormProduto extends javax.swing.JFrame {
      
    /** Creates new form FormularioExemplo2 */
    public FormProduto() {
        initComponents();
    }
       
   
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        painelBotoes = new javax.swing.JPanel();
        bNovo = new javax.swing.JButton();
        bAltera = new javax.swing.JButton();
        bRemove = new javax.swing.JButton();
        bCancela = new javax.swing.JButton();
        painelPrincipal = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        bNovo.setText("Novo");
        bNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bNovoActionPerformed(evt);
            }
        });
        painelBotoes.add(bNovo);

        bAltera.setText("Altera");
        painelBotoes.add(bAltera);

        bRemove.setText("Remove");
        bRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bRemoveActionPerformed(evt);
            }
        });
        painelBotoes.add(bRemove);

        bCancela.setText("Cancela");
        bCancela.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCancelaActionPerformed(evt);
            }
        });
        painelBotoes.add(bCancela);

        getContentPane().add(painelBotoes, java.awt.BorderLayout.PAGE_END);

        tabela.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        tabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Código", "Nome"
            }
        ));
        jScrollPane1.setViewportView(tabela);
        tabela.getColumnModel().getColumn(0).setPreferredWidth(2);
        tabela.getColumnModel().getColumn(1).setPreferredWidth(200);

        javax.swing.GroupLayout painelPrincipalLayout = new javax.swing.GroupLayout(painelPrincipal);
        painelPrincipal.setLayout(painelPrincipalLayout);
        painelPrincipalLayout.setHorizontalGroup(
            painelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelPrincipalLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE))
        );
        painelPrincipalLayout.setVerticalGroup(
            painelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelPrincipalLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
                .addContainerGap())
        );

        getContentPane().add(painelPrincipal, java.awt.BorderLayout.PAGE_START);

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

    
    
    private void bNovoActionPerformed(java.awt.event.ActionEvent evt) {                                      
       new FormEdicaoProduto().setVisible(true);     
}                                     

    private void bCancelaActionPerformed(java.awt.event.ActionEvent evt) {                                         
        dispose();
    }                                        

    private void bRemoveActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
    }                                       
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[])  {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormProduto().setVisible(true);
            }
        });
       
    }
    
    // Variables declaration - do not modify                     
    private javax.swing.JButton bAltera;
    private javax.swing.JButton bCancela;
    private javax.swing.JButton bNovo;
    private javax.swing.JButton bRemove;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel painelBotoes;
    private javax.swing.JPanel painelPrincipal;
    private javax.swing.JTable tabela;
    // End of variables declaration                   
    
}
FormEdicaoProduto.java
package aula20080726;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class FormEdicaoProduto extends javax.swing.JFrame {

  public void pesquisachave()throws ClassNotFoundException{
        ProdutoProcessa pesquisachave = new ProdutoProcessa();
       
        JOptionPane.showMessageDialog(null,  pesquisachave.getCodigo());
       // tCodigo.setText(String.valueOf(pesquisachave.pesquisa()));        
  }

    
    public FormEdicaoProduto() {
        initComponents();
    }
      
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        painelBotoes = new javax.swing.JPanel();
        bSalvar = new javax.swing.JButton();
        bCancelar = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        painelPrincipal = new javax.swing.JPanel();
        lCodigo = new javax.swing.JLabel();
        lNome = new javax.swing.JLabel();
        tCodigo = new javax.swing.JTextField();
        tNome = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        bSalvar.setText("Salvar");
        bSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bSalvarActionPerformed(evt);
            }
        });
        painelBotoes.add(bSalvar);

        bCancelar.setText("Cancelar");
        bCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCancelarActionPerformed(evt);
            }
        });
        painelBotoes.add(bCancelar);

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

        getContentPane().add(painelBotoes, java.awt.BorderLayout.PAGE_END);

        lCodigo.setText("Codigo:");

        lNome.setText("Nome:");

        tCodigo.setEditable(false);

        javax.swing.GroupLayout painelPrincipalLayout = new javax.swing.GroupLayout(painelPrincipal);
        painelPrincipal.setLayout(painelPrincipalLayout);
        painelPrincipalLayout.setHorizontalGroup(
            painelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelPrincipalLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(painelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lNome, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lCodigo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(painelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tNome, javax.swing.GroupLayout.DEFAULT_SIZE, 339, Short.MAX_VALUE)
                    .addComponent(tCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        painelPrincipalLayout.setVerticalGroup(
            painelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelPrincipalLayout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(painelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lCodigo)
                    .addComponent(tCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(painelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lNome))
                .addContainerGap(15, Short.MAX_VALUE))
        );

        getContentPane().add(painelPrincipal, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>                        
  
    private void bSalvarActionPerformed(java.awt.event.ActionEvent evt) {                                        
      ProdutoProcessa novoproduto = new ProdutoProcessa();
      novoproduto.insere(Integer.parseInt(tCodigo.getText()), tNome.getText());

}                                       

    private void bCancelarActionPerformed(java.awt.event.ActionEvent evt) {                                          
        dispose();
    }                                         

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            pesquisachave();                                        
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(FormEdicaoProduto.class.getName()).log(Level.SEVERE, null, ex);
        }
}
    
    
   
    // Variables declaration - do not modify                     
    private javax.swing.JButton bCancelar;
    private javax.swing.JButton bSalvar;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel lCodigo;
    private javax.swing.JLabel lNome;
    private javax.swing.JPanel painelBotoes;
    private javax.swing.JPanel painelPrincipal;
    private javax.swing.JTextField tCodigo;
    private javax.swing.JTextField tNome;
    // End of variables declaration                   
    
}

Pessoal, obrigado por enquanto.

abraços...

2 Respostas

BrunoBastosPJ

Como você está persistindo objetos em um arquivo texto fica realmente complicado encontrar uma maneira eficiente de obter o último código…
O que você pode fazer é ter um outro arquivo txt que você guarde este código, ou então fazer um loop e pegar o último objeto persistido.

O loop ficaria assim

public int getNextCode() {
 Produto p = null;
 try {  
     File file = new File("produto1.txt");  
     ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));  
     Object paux = null;
     while((paux=in.readObject()) != null) {
            p = (Produto)paux; 
     } 
            in.close();  
  } catch (IOException e) {  
    e.printStackTrace();  
  }
  return (p.getCodigo()+1);  
}

Não joguei este código no Netbeans, então se o loop der algum erro substitua ele por

while(true) {
  paux = in.readObject();
  if(paux != null) {
      p (Produto) paux;
  } else {
     break;
  }
}

Tentei usar a menor POG possível, mas foi difícil :razz:

T

Obrigado Bruno,
Não tinha pensado nisto…

Vou testar o codigo depois posto aqui,

Abraços…

Criado 29 de julho de 2008
Ultima resposta 30 de jul. de 2008
Respostas 2
Participantes 2