Oi pessoal eu to criando um projeto em java, mas o problema eh que a minha classe principal esta muito grande, pra estruturar melhor o meu código eu fiz o seguinte na classe principal eu criei três botões, nos dois primeiros botões as suas ações estão na classe principal, mas o terceiro botão eu criei uma classe separada com suas funções que eh de consultar no banco de dados e depois imprimir no TextArea, como eu queria saber se realmente funcionar o botão eu criei ele dentro de frame e também criei o TextArea para imprimir o resultado da consulta a minha duvida eh como eu posso fazer para quando eu clicar no botão de consulta no banco da minha classe principal ele executar a função da minha classe botão, ai esta o código, ah lembrando que a minha classe principal eh a classe Layout
package teste;
import teste.ConsultaBanco;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileWriter;
public class Layout extends JFrame implements ActionListener {
private JTextArea TxtArquivo;
private JFileChooser Arquivo;
private JButton CmdEscolher, CmdSalvar, CmdConsulta;
private JScrollPane js;
private void setCenter(JFrame frame) {
Dimension paneSize = frame.getSize();
Dimension screenSize = frame.getToolkit().getScreenSize();
frame.setLocation( (screenSize.width - paneSize.width) / 2, (screenSize.height - paneSize.height) / 2);
}
public Layout(){
setSize(400, 450);
setResizable(false);
setTitle("Abrindo um arquivo TXT");
setCenter(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = getContentPane();
cp.setLayout(null);
Arquivo = new JFileChooser(".");
CmdSalvar = new JButton("Salvar arquivo");
CmdSalvar.setBounds(50,10,140,25);
CmdSalvar.addActionListener(this);
cp.add(CmdSalvar);
CmdEscolher = new JButton("Escolher arquivo");
CmdEscolher.setBounds(200,10,140,25);
CmdEscolher.addActionListener(this);
cp.add(CmdEscolher);
CmdConsulta = new JButton ("Consulta no Banco");
CmdConsulta.setBounds(120, 350, 140, 25);
CmdConsulta.addActionListener(this);
cp.add(CmdConsulta);
TxtArquivo = new JTextArea();
TxtArquivo.setLineWrap(true);
js = new JScrollPane(TxtArquivo);
js.setBounds(5,40,385,280);
js.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
cp.add(js);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == CmdEscolher){
Arquivo.setBackground(Color.black);
int res = Arquivo.showOpenDialog(this);
if(res == JFileChooser.APPROVE_OPTION){
File arq = Arquivo.getSelectedFile();
try{
TxtArquivo.setText(retornaString(arq.getPath()));
} catch(Exception ex){
JOptionPane.showMessageDialog(null, "Não foi possível abrir o arquivo" + arq.getPath() + "!", "Leitura de arquivo", JOptionPane.ERROR_MESSAGE);
}
}
}
e essa eh a classe do butao onde contem a função que eu quero que o butão de consulta no banco da classe layout execute
package teste;
import teste.Layout;
public class ConsultaBanco extends JFrame implements ActionListener{
private String Drive = "oracle.jdbc.OracleDriver";
private String URL= "jdbc:oracle:thin:@bkpcomercial:1521:mantger";
private String USARNAME = "mri";
private String PASSWORD = "mri";
private Connection conn;
private JScrollPane js;
private JFileChooser Arquivo;
private JButton Cmdconsulta;
private JTextArea TxtArquivo;
public ConsultaBanco(){
try{
Class.forName(this.Drive);
this.conn = DriverManager.getConnection(URL, USARNAME, PASSWORD);
} catch (ClassNotFoundException e){
System.out.println("Não foi possivel encontrar o driver de banco: " + e.getMessage());
} catch(SQLException e){
System.out.println("Erro ao conectar com o banco: " + e.getMessage());
}
setSize(400, 450);
setResizable(false);
setTitle("Botao de consulta para teste");
//setCenter(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = getContentPane();
cp.setLayout(null);
Arquivo = new JFileChooser(".");
Cmdconsulta = new JButton ("Consulta no Banco");
Cmdconsulta.setBounds(120, 350, 140, 25);
Cmdconsulta.addActionListener(this);
cp.add(Cmdconsulta);
TxtArquivo = new JTextArea();
TxtArquivo.setLineWrap(true);
js = new JScrollPane(TxtArquivo);
js.setBounds(5,40,385,280);
js.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
cp.add(js);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == Cmdconsulta){
try{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
String url = "jdbc:oracle:thin:@bkpcomercial:1521:mantger";
this.conn = DriverManager.getConnection (url, "mri", "mri");
Statement st = conn.createStatement();
System.out.println("Conectado");
int i =0;
ResultSet rs = st.executeQuery("select lig.*, spc.* from mri.cb_cobr_spc spc, mri.cb_cobr_ligacao lig where nom_arquivo_inc = '1386' and spc.cod_programa = lig.cod_programa and spc.num_ligacao = lig.num_ligacao");
System.out.println("Consultando");
//imprimindo a o resutado
while( rs.next()){
//declaracao de variaveis
String strNovaStrig = " ";
String strZero ="0";
String strnom_cliente = rs.getString("nom_cliente"); // nome do cliente
String str_tipodoc = null;
String strendereco_leit = rs.getString("endereco_leit"); //endereco do cliente
String strcpf = rs.getString("cpf");//cpf
String strcgc = rs.getString("cgc");//cgc
//ta faltando do numero da ksa dio cliente
String strnom_bairro_leit = rs.getString("nom_bairro_leit");//nome do bairro
String strcod_cep_leit = rs.getString("cod_cep_leit");//cep do cliente
String strnum_residencial = rs.getString("num_residencial"); // numero do telefone*/
String str_contador = null;
strnom_cliente = BarraCaracteres.BarraCaracteres(strnom_cliente, 45);//chamando a funcao barraCaracteres para imprimir somente os primeiros 45 caracteres
strnom_cliente = InserirEspaco.InserirEspaco(strnom_cliente, 45);//chamando a funcao inserir espaco quando o nome do cliente tiver menos que 45 caracteres
strendereco_leit = BarraCaracteres.BarraCaracteres(strendereco_leit, 50);//chamando a funcao barraCaracteres para imprimir somente os primeiros 50 caracteres
strnom_bairro_leit = BarraCaracteres.BarraCaracteres(strnom_bairro_leit, 25);//chamando a funcao barraCaracteres para imprimir somente os primeiros 25 caracteres
strcod_cep_leit = InserirZero.ZeroDireita(strcod_cep_leit, 8);////chamando a funcao inseri zero para preencher com zeros os caracteres do cep do cliente
System.out.println(strnom_cliente);
//if para imprimir o cpf e cgc com insersao de zeros quando nulos valores
if ((strcpf == null) | (strcpf == "")){
if ((strcgc != null) & (strcgc != "")){
strcpf = strcgc;
str_tipodoc = "1";
}else {
strcpf = "00000000";
str_tipodoc = " ";
}
}else {
str_tipodoc = "2";
}
strcpf = InserirZero.InserirZero(strcpf, 15);
if(strnum_residencial == null){
strnum_residencial = "00000000";
}
//para inserir contadores no final de cada linha
str_contador = String.valueOf(i + 1);
i = (i + 1);
strnum_residencial = SemValores.SemValores(strnum_residencial, 8);//inseri tres na frente dos numeros de telefones
strnum_residencial = BarraCaracteres.BarraCaracteres(strnum_residencial, 8);//imprimi somente os 8 primeiros digitos da tabela de telefone
str_contador = InserirZero.InserirZero(str_contador, 6);//inseri zeros na frente do numero sequencial de cada linha ate complentar 6 caracteres
TxtArquivo.append("01"); //tipo do registro
TxtArquivo.append("69029160"); //praca de concessao
TxtArquivo.append(strnom_cliente);// nome do cliente
TxtArquivo.append(str_tipodoc);//TIPO DE DOCUMENTO
TxtArquivo.append(strcpf);//CPF OU CGC
TxtArquivo.append(BarraCaracteres.StringOfChar(strNovaStrig, 20)); //numero de RG
TxtArquivo.append(BarraCaracteres.StringOfChar(strNovaStrig, 8)); //DATA DE NASCIMENTO
TxtArquivo.append(BarraCaracteres.StringOfChar(strNovaStrig, 45)); //FILIACAO
TxtArquivo.append(strendereco_leit);//endereco do cliente
TxtArquivo.append(BarraCaracteres.StringOfChar(strZero, 5));//numero DA KSA DO cliente
TxtArquivo.append(BarraCaracteres.StringOfChar(strNovaStrig, 30)); //COMPLEMENTO
TxtArquivo.append(strnom_bairro_leit);//nome do bairro
TxtArquivo.append(strcod_cep_leit);//CEP DO CLIENTE
TxtArquivo.append("Manaus");//CIDADE
TxtArquivo.append(BarraCaracteres.StringOfChar(strNovaStrig, 24));
TxtArquivo.append("AM");//UF
TxtArquivo.append("92");//FONE DDD
TxtArquivo.append(BarraCaracteres.StringOfChar(strNovaStrig, 20)); //BRANCOS
TxtArquivo.append(strnum_residencial);//NUMERO DO TELEFONE
TxtArquivo.append(BarraCaracteres.StringOfChar(strZero, 10));//codigo de retorno*/
TxtArquivo.append(str_contador);//sEquencial de registro
TxtArquivo.append(" \n");
//dados referentes aos debitos
String strDataVencimento = rs.getString("dat_vencto");//6
String strData_registro = rs.getString("dat_compra");//7
String strValorDebito = rs.getString("val_debito");//8
String strcod_programa = rs.getString("cod_programa");//9
String strnum_ligacao = rs.getString("num_ligacao");//10
strDataVencimento = InserirZero.InserirZero(strDataVencimento, 8);
strData_registro = InserirZero.InserirZero(strData_registro, 8);
strValorDebito = InserirZero.ZeroDireita(strValorDebito, 13);
strcod_programa = InserirEspaco.InserirEspaco(strcod_programa, 30);
strnum_ligacao = InserirZero.InserirZero(strnum_ligacao, 8);
//para inserir contadores no final de cada linha
str_contador = String.valueOf(i + 1);
i = (i + 1);
str_contador = InserirZero.InserirZero(str_contador, 6);//inseri zeros na frente do numero sequencial de cada linha ate complentar 6 caracteres
System.out.println(strDataVencimento);
TxtArquivo.append("02");//1- tipo de registro
TxtArquivo.append(str_tipodoc);//2- tipo de documento
TxtArquivo.append(strcpf);//3- cpf ou cgc
TxtArquivo.append("I");//4-codigo de operacao
TxtArquivo.append("C");//5- comprador, fiador, avalista
TxtArquivo.append(strDataVencimento);//6- data do vencmento
TxtArquivo.append(strData_registro);//7- data do egistro
TxtArquivo.append(strValorDebito);//8- valor do debito
TxtArquivo.append(strcod_programa);//9- numero de aviso
TxtArquivo.append(strnum_ligacao);//10- numero da ligacao
TxtArquivo.append(BarraCaracteres.StringOfChar(strZero, 2));//11- natureza da inclusao
TxtArquivo.append(BarraCaracteres.StringOfChar(strZero, 3));//12- motivo da inclusao
TxtArquivo.append(BarraCaracteres.StringOfChar(strNovaStrig, 232));//13- brancos
TxtArquivo.append(BarraCaracteres.StringOfChar(strZero, 10));//14- codigo de retorno
TxtArquivo.append(str_contador);
TxtArquivo.append(" \n");
}
rs.close();
st.close();
conn.close();
//mensagem de erro para quando ocorrer problemas na conexao com o banco de dados
}catch(SQLException e1){
System.out.println("Erro ao conectar ao banco");
e1.printStackTrace();
}finally{ // Finalizando a conexão
System.out.println("Encerrando a conexão");
}
}
}
public static void main(String[] args) {
ConsultaBanco app = new ConsultaBanco();
String url = "jdbc:oracle:thin:@bkpcomercial:1521:mantger";
app.show();
}
}
if(e.getSource() == CmdSalvar){
int res = Arquivo.showSaveDialog(this);
if(res == JFileChooser.APPROVE_OPTION){
File arq = Arquivo.getSelectedFile();
try{
escreveArquivo(TxtArquivo.getText(), arq.getPath());
} catch(IOException ioe){
JOptionPane.showMessageDialog(null, "Não foi possível salvar arquivo!");
}
}
}
}
public String retornaString(String fileName) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(fileName));
String line;
StringBuffer buffer = new StringBuffer();
while( (line = in.readLine()) != null ){
buffer.append(line + "\n");
}
in.close();
return buffer.toString();
}
public void escreveArquivo(String conteudo, String fileName) throws IOException {
PrintWriter out = new PrintWriter(new FileWriter(fileName));
out.print(conteudo);
out.close();
JOptionPane.showMessageDialog(null, "Arquivo salvo com sucesso!");
}
public static void main(String args[]) {
Layout app = new Layout();
app.show();
}
}
alguem ai sabe me dizer como que eu posso faço isso
Se alguem soubel me ajude por favor
bjokas
EDIT - Use as tags CODE, por favor. Além disso “butão” é um país asiático.