Duplo problema em um codigo

6 respostas
AndreBatista

Ola,bom dia!
Sempre observei esse fórum sempre tirei minhas duvidas pesquisando nos tópicos,mas agora apareceu uma duvida nesse código:

import java.awt.Color;

import java.awt.FileDialog;

import java.awt.FlowLayout;

import java.awt.TextArea;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import javax.swing.*;
class Programa extends JFrame implements ActionListener

{

JLabel label1,label2;

JButton btGravar,btAbrir,btLimpar;

JTextField tfTexto;

TextArea textArea1;

JPanel panel1;

FileDialog fdAbrir,fdSalvar;

public static void main(String[] args)

{

JFrame janela = new Programa();

janela.setUndecorated(true);

janela.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);

janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

janela.setVisible(true);

}

Programa()

{

setTitle(Manipulação de arquivo Texto);

setBounds (250,50,500,300);

setResizable(false);

getContentPane().setBackground(new Color (150,150,150));

getContentPane().setLayout (new FlowLayout());

label1 = new JLabel(Texto a ser editado:);

label2 = new JLabel(Status:);

label1.setForeground(Color.black);

label2.setForeground(Color.black);

btGravar = new JButton(Gravar);

btAbrir = new JButton(Abrir);

btAbrir = new JButton(Limpar);

btGravar.addActionListener(this);

btAbrir.addActionListener(this);

btLimpar.addActionListener(this);

tfTexto = new JTextField(35);

tfTexto.setForeground(Color.red);

tfTexto.setEditable(false);

panel1 = new JPanel();

panel1.setLayout (new FlowLayout());

panel1.add(label2); panel1.add(tfTexto);

textArea1 = new TextArea(8,60);

fdAbrir = new FileDialog(this,Abrir arquivo,FileDialog.LOAD);

fdSalvar = new FileDialog(this,Salvar arquivo,FileDialog.SAVE);

getContentPane().add(label1);

getContentPane().add(textArea1);

getContentPane().add(btGravar);

getContentPane().add(btAbrir);

getContentPane().add(btLimpar);

getContentPane().add(panel1);

}

<a class="mention" href="/u/override">@Override</a>

public void actionPerformed(ActionEvent e)

{

String nome_do_arquivo;

if (e.getSource() == btLimpar)

{

textArea1.setText("");

tfTexto.setText("");

}

if (e.getSource() == btGravar)

{

try

{

fdSalvar.setVisible(true);

if (fdSalvar.getFile()==null) return;

nome_do_arquivo = fdSalvar.getDirectory()+fdSalvar.getFile();

FileWriter out = new FileWriter(nome_do_arquivo);

out.write(textArea1.getText());

tfTexto.setText(“Arquivo gravado com sucesso !”);

}

catch(IOException erro)

{

tfTexto.setText(“Erro ao gravar no arquivo !”);

}

}

if (e.getSource() == btAbrir)

{

try

{

fdAbrir.setVisible(true);

if (fdAbrir.getFile()==null) return;

nome_do_arquivo = fdAbrir.getDirectory()+fdAbrir.getFile();

try (FileReader in = new FileReader(nome_do_arquivo)) {

String s = “”;

int i = in.read();

while (i!=-1)

{

s = s +(char)i;

i = in.read();

}

textArea1.setText(s);

}

tfTexto.setText(“Arquivo aberto com sucesso !”);

}

catch(IOException erro)

{

tfTexto.setText(“Erro ao abrir o arquivo !”);

}

}

}
}
Está dando esse erro:
Exception in thread main java.lang.NullPointerException

at Programa.(Programa.java:44)

at Programa.main(Programa.java:22)

Java Result: 1

Outra duvida…
O que modifico nesse código para me conectar a um banco de dados MySQL,
Estou criando esse código para um programa base de cadastro de cliente

6 Respostas

otaviojava

Para ajudar tenta usar a tag code.
Desse modo o código fica mais fácil de entender.

import java.awt.Color; 
import java.awt.FileDialog; 
import java.awt.FlowLayout; 
import java.awt.TextArea; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.IOException; 
import javax.swing.*; 

class Programa extends JFrame implements ActionListener 
{ 
JLabel label1,label2; 
JButton btGravar,btAbrir,btLimpar; 
JTextField tfTexto; 
TextArea textArea1; 
JPanel panel1; 
FileDialog fdAbrir,fdSalvar; 
public static void main(String[] args) 
{ 
JFrame janela = new Programa(); 
janela.setUndecorated(true); 
janela.getRootPane().setWindowDecorationStyle(JRootPane.FRAME); 
janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
janela.setVisible(true); 
} 
Programa() 
{ 
setTitle("Manipulação de arquivo Texto"); 
setBounds (250,50,500,300); 
setResizable(false); 
getContentPane().setBackground(new Color (150,150,150)); 
getContentPane().setLayout (new FlowLayout()); 
label1 = new JLabel("Texto a ser editado:"); 
label2 = new JLabel("Status:"); 
label1.setForeground(Color.black); 
label2.setForeground(Color.black); 
btGravar = new JButton("Gravar"); 
btAbrir = new JButton("Abrir"); 
btAbrir = new JButton("Limpar"); 
btGravar.addActionListener(this); 
btAbrir.addActionListener(this); 
btLimpar.addActionListener(this); 
tfTexto = new JTextField(35); 
tfTexto.setForeground(Color.red); 
tfTexto.setEditable(false); 
panel1 = new JPanel(); 
panel1.setLayout (new FlowLayout()); 
panel1.add(label2); panel1.add(tfTexto); 
textArea1 = new TextArea(8,60); 
fdAbrir = new FileDialog(this,"Abrir arquivo",FileDialog.LOAD); 
fdSalvar = new FileDialog(this,"Salvar arquivo",FileDialog.SAVE); 
getContentPane().add(label1); 
getContentPane().add(textArea1); 
getContentPane().add(btGravar); 
getContentPane().add(btAbrir); 
getContentPane().add(btLimpar); 
getContentPane().add(panel1); 
} 
@Override 
public void actionPerformed(ActionEvent e) 
{ 
String nome_do_arquivo; 
if (e.getSource() == btLimpar) 
{ 
textArea1.setText(""); 
tfTexto.setText(""); 
} 
if (e.getSource() == btGravar) 
{ 
try 
{ 
fdSalvar.setVisible(true); 
if (fdSalvar.getFile()==null) return; 
nome_do_arquivo = fdSalvar.getDirectory()+fdSalvar.getFile(); 
FileWriter out = new FileWriter(nome_do_arquivo); 
out.write(textArea1.getText()); 
tfTexto.setText("Arquivo gravado com sucesso !"); 
} 
catch(IOException erro) 
{ 
tfTexto.setText("Erro ao gravar no arquivo !"); 
} 
} 
if (e.getSource() == btAbrir) 
{ 
try 
{ 
fdAbrir.setVisible(true); 
if (fdAbrir.getFile()==null) return; 
nome_do_arquivo = fdAbrir.getDirectory()+fdAbrir.getFile(); 
try (FileReader in = new FileReader(nome_do_arquivo)) { 
String s = ""; 
int i = in.read(); 
while (i!=-1) 
{ 
s = s +(char)i; 
i = in.read(); 
} 
textArea1.setText(s); 
} 
tfTexto.setText("Arquivo aberto com sucesso !"); 
} 
catch(IOException erro) 
{ 
tfTexto.setText("Erro ao abrir o arquivo !"); 
} 
} 
} 


}
otaviojava

você não instânciou o objeto btLimpar.
E ele por padrão é nulo.
Dai o motivo da sua exceção.

AndreBatista

Otavio, primeiramente obrigado pelas dicas.
Mas…
Não entendi esse instanciou o objeto btLimpar,
Infelizmente ainda não entendo todas as linguagens que vocês usam,
você poderia ser mais “claro” para mim!
rsrs
e a parte da conexão com o banco de dados?
Eu peguei um conector de mysql com o java mas não sei como implementar isso no codigo…
pesquisei em alguns livros, mas os mesmos só direcionam para acess…

otaviojava

Perfeito.
Você precisa criar o objeto antes de usar.
É o lance do

Objeto objeto=new Objeto();
objeto.metodo();

Se vc não cria o objeto e o usa dará exceção de NullPointerException

objeto.metodo();
AndreBatista

Muito obrigado Otavio!!
Quando fui instanciar eu coloquei o btAbrir duas vezes, mas que na verdade era btAbrir e btLimpar.

E sobre o banco de dados você tem alguma ideia?

otaviojava

dá uma olhada em jdbc.

Criado 14 de junho de 2012
Ultima resposta 14 de jun. de 2012
Respostas 6
Participantes 2