Prezados(as);
Como segue no cód. abaixo, preciso salvar atributos do objeto PessoaIMC em um arquivo txt [arq.txt].
1- Como faço para salvar um objeto em arquivo?
2- Seria possível utilizar a estrutura try/catch para gravação/leitura dentro de um método e ñ somente no main, como tenho observado? Como?
3- Qual a melhor solução gravação/leitura: dentro dum método o no main mesmo?
Desde já conto com a colaboração e atenção de todos;
Muito Obrigado! :thumbup:
package pessoaimc;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
/**
*
* @author Fabao
*/
public class PessoaIMC extends JFrame implements ActionListener
{
String nome,
sexo;
float peso,
altura,
imc;
JLabel Nome,
Sexo,
Peso,
Altura,
Imc,
vazio1,
vazio2,
vazio3;
JButton calcH,
calcM,
limpar;
JTextField _nome,
_sexo,
_peso,
_altura,
_imc;
static TextArea text;
public PessoaIMC()
{
this.nome = "";
this.sexo = "";
this.altura = 0;
this.peso = 0;
this.imc = 0;
}
PessoaIMC(PessoaIMC p)
{
setTitle("Calculo IMC");
setSize(350, 225);
setLocation(50,50);
getContentPane().setBackground(new Color(100,123,150));
getContentPane().setLayout(new GridLayout(5,3));
Nome = new JLabel("Nome: ");
Nome.setForeground(Color.black);
Nome.setFont(new Font("",Font.BOLD, 25));
Sexo = new JLabel("Sexo: ");
Sexo.setForeground(Color.black);
Sexo.setFont(new Font ("", Font.BOLD, 25));
Peso = new JLabel("Peso: ");
Peso.setForeground(Color.black);
Peso.setFont(new Font ("", Font.BOLD, 25));
Altura = new JLabel ("Altura: ");
Altura.setForeground(Color.black);
Altura.setFont(new Font ("", Font.BOLD, 25));
Imc = new JLabel ("IMC");
Imc.setForeground (Color.yellow);
Imc.setFont (new Font ("", Font.BOLD, 25));
vazio1 = new JLabel ("");
vazio1.setForeground(Color.white);
vazio2 = new JLabel ("");
vazio2.setForeground(Color.white);
vazio3 = new JLabel ("");
vazio3.setForeground(Color.white);
_nome = new JTextField();
_sexo = new JTextField();
_sexo.setEditable(false);
_peso = new JTextField();
_altura = new JTextField();
_imc = new JTextField();
_imc.setEditable(false);
calcH = new JButton ("IMC Homem");
calcH.addActionListener(this);
calcM = new JButton ("IMC Mulher");
calcM.addActionListener (this);
limpar = new JButton ("LIMPAR");
limpar.addActionListener(this);
limpar.setBackground(Color.yellow);
limpar.setForeground(Color.red);
text = new TextArea();
//Formatação do Layout L5xC3
getContentPane().add(Nome);
getContentPane().add(_nome);
getContentPane().add(calcH);
getContentPane().add(Altura);
getContentPane().add(_altura);
getContentPane().add(calcM);
getContentPane().add(Peso);
getContentPane().add(_peso);
getContentPane().add(limpar);
getContentPane().add(Sexo);
getContentPane().add(_sexo);
getContentPane().add(vazio1);
getContentPane().add(Imc);
getContentPane().add(_imc);
getContentPane().add(vazio2);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == limpar)
{
_nome.setText("");
_sexo.setText("");
_peso.setText("");
_altura.setText("");
_imc.setText("");
text.setText("");
return;
}
try
{
this.nome = _nome.getText();
//this.sexo = _sexo.getText();
this.peso = Float.parseFloat(_peso.getText());
this.altura = Float.parseFloat(_altura.getText());
/**
* IMC = peso / (altura)²
*
* Abaixo do peso:
* M MAIOR 19,1
* H MENOR 20,7
*
* Peso ideal:
* Mulheres 19,1 - 25,8
* Homens 20,7 - 26,4
*
* Acima disto considere como obeso.
*/
this.imc = (float) (this.peso / Math.pow(this.altura,2));
if(e.getSource() == calcM)
{
_sexo.setText("Mulher");
this.sexo = _sexo.getText();
if (this.imc < 19.1)
{
_imc.setText("Abaixo do Peso! " + this.imc);
return;
}
else if(this.imc >= 19.1 && this.imc <= 25.8)
{
_imc.setText("Peso Ideal! " + this.imc);
return;
}
else if(this.imc > 25.8)
{
_imc.setText("Obeso! " + this.imc);
return;
}
}
else if (e.getSource() == calcH)
{
_sexo.setText("Homem");
this.sexo = _sexo.getText();
if (this.imc < 19.1)
{
_imc.setText("Abaixo do Peso! " + this.imc);
return;
}
else if(this.imc >= 19.1 && this.imc <= 25.8)
{
_imc.setText("Peso Ideal! " + this.imc);
return;
}
else if(this.imc > 25.8)
{
_imc.setText("Obeso! " + this.imc);
return;
}
}
}
catch (NumberFormatException erro)
{
_imc.setText("Erro");
return;
}
}
public static void main(String[] args)
{
PessoaIMC pessoa = new PessoaIMC();
JFrame Janela = new PessoaIMC(pessoa);
Janela.setVisible(true);
try
{
//Gera o arquivo para armazenar o objeto
FileOutputStream arquivoGrav = new FileOutputStream("D:/Users/Fabao/IFES/LP1/Projetos NetBeens/Swing/arq.txt");
//Classe responsavel por inserir os objetos
ObjectOutputStream objGravar = new ObjectOutputStream(arquivoGrav);
//Grava o objeto cliente no arquivo
objGravar.writeObject(pessoa);
objGravar.flush();
objGravar.close();
arquivoGrav.flush();
arquivoGrav.close();
System.out.println("Objeto gravado com sucesso!");
//text.setText("Objeto gravado com sucesso!");
}
catch( Exception e )
{
e.printStackTrace( );
}
System.out.println("Recuperando objeto: ");
//text.setText("Recuperando objeto: ");
try
{
//Carrega o arquivo
FileInputStream arquivoLeitura =
new FileInputStream("D:/Users/Fabao/IFES/LP1/Projetos NetBeens/Swing/arq.txt");
//Classe responsavel por recuperar os objetos do arquivo
ObjectInputStream objLeitura = new ObjectInputStream(arquivoLeitura);
System.out.println(objLeitura.readObject());
//text.setText("" + objLeitura.readObject());
objLeitura.close();
arquivoLeitura.close();
}
catch( Exception e )
{
e.printStackTrace( );
}
//para fechar a janela
Janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}