Criar mainJFrame

3 respostas
J

Boa tarde pessoal,

Meu primeiro post por isso me corrijam se houver algum erro por favor.

Estou desenvolvimento uma aplicação em java que vai interagir com um banco de dados e gravar as informações que o usuário digitar lá, eu consegui criar uma JFrame que já está funcionando mas agora quero criar uma Main que vai chamar essa e outras que vou criar também quero que nelas tenha um botão para encerrar a JFrame e voltar para a Main, vou postar o código completo do projeto se puderem me ajudar agradeço.

[i]essa é a JFrame que fiz:

package consultoria.frame;

import consultoria.controller.ColaboradorController;
 
@SuppressWarnings("serial")
public class ColaboradorFrame extends JFrame {
 
    private JLabel lbMat_colab, lbNome, lbCargo, lbId_centro_custo;
    private JTextField txtMat_colab, txtNome, txtCargo, txtId_centro_custo, txtLocalizar;
    private JButton btnSalvar, btnAlterar, btnExcluir, btnClear, btnLocalizar;
    private JButton btnPrimeiro, btnProximo, btnAnterior, btnUltimo;
 
    private List<Colaborador> colaboradorList = new ColaboradorController().listaColaborador();
    private int registroAtual = 0;
 
    public ColaboradorFrame() {
        super("Colaborador");
        Container tela = getContentPane();
        getContentPane().setLayout(null);
        lbMat_colab = new JLabel("Matricula com 5 digitos");
        lbNome = new JLabel("Nome");
        lbCargo = new JLabel("Cargo");
        lbId_centro_custo = new JLabel("Centro de custo com 4 digitos");
 
        lbMat_colab.setBounds(10,10,240,15);
        lbNome.setBounds(10, 50, 240, 15);
        lbCargo.setBounds(10, 90, 240, 15);
        lbId_centro_custo.setBounds(10, 136, 240, 15);
 
        lbMat_colab.setForeground(Color.BLACK);
        lbNome.setForeground(Color.BLACK);
        lbCargo.setForeground(Color.BLACK);
        lbId_centro_custo.setForeground(Color.BLACK);
 
        lbMat_colab.setFont(new Font("Courier New", Font.BOLD, 14));
        lbNome.setFont(new Font("Courier New", Font.BOLD, 14));
        lbCargo.setFont(new Font("Courier New", Font.BOLD, 14));
        lbId_centro_custo.setFont(new Font("Courier New", Font.BOLD, 14));
 
        tela.add(lbMat_colab);
        tela.add(lbNome);
        tela.add(lbCargo);
        tela.add(lbId_centro_custo);
 
        txtMat_colab = new JTextField();
        txtNome = new JTextField();
        txtCargo = new JTextField();
        txtId_centro_custo = new JTextField();
 
        txtMat_colab.setBounds(10, 25, 174, 20);
        txtNome.setBounds(10, 65, 265, 20);
        txtCargo.setBounds(10, 105, 265, 20);
        txtId_centro_custo.setBounds(10, 158, 100, 20);
 
        tela.add(txtMat_colab);
        tela.add(txtNome);
        tela.add(txtCargo);
        tela.add(txtId_centro_custo);
 
        btnSalvar = new JButton("Salvar");
        btnAlterar = new JButton("Alterar");
        btnExcluir = new JButton("Excluir");
        btnClear = new JButton("Limpar");
        btnPrimeiro = new JButton("|<");
        btnAnterior = new JButton("<<");
        btnProximo = new JButton(">>");
        btnUltimo = new JButton(">|");
 
        btnSalvar.setBounds(336, 47, 80, 20);
        btnAlterar.setBounds(336, 87, 80, 20);
        btnExcluir.setBounds(336, 131, 80, 20);
 
        tela.add(btnSalvar);
        tela.add(btnAlterar);
        tela.add(btnExcluir);
 
        btnPrimeiro.setBounds(36, 260, 50, 20);
        btnAnterior.setBounds(96, 260, 50, 20);
        btnClear.setBounds(156, 260, 75, 20);
        btnProximo.setBounds(241, 260, 50, 20);
        btnUltimo.setBounds(301, 260, 50, 20);
 
        tela.add(btnPrimeiro);
        tela.add(btnAnterior);
        tela.add(btnClear);
        tela.add(btnProximo);
        tela.add(btnUltimo);
 
        JLabel lbLocalizar = new JLabel("Localizar por nome");
        lbLocalizar.setBounds(10, 187, 220, 20);
 
        txtLocalizar = new JTextField();
        txtLocalizar.setBounds(10, 207, 220, 20);
 
        btnLocalizar = new JButton("Ir");
        btnLocalizar.setBounds(235, 207, 55, 20);
 
        tela.add(lbLocalizar);
        tela.add(txtLocalizar);
        tela.add(btnLocalizar);
 
        setSize(488, 386);
        setVisible(true);
        setLocationRelativeTo(null);
 
        btnSalvar.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onClickSalvar();
                    }
                }
        );
 
        btnAlterar.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onClickAlterar();
                    }
                }
        );
 
        btnExcluir.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onClickExcluir();
                    }
                }
        );
 
        btnClear.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        clearFields();
                        registroAtual = 0;
                    }
                }
        );
 
        btnLocalizar.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onClickLocalizar();
                    }
                }
        );
 
        btnPrimeiro.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onClickPrimeiro();
                    }
                }
        );
        btnAnterior.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onClickAnterior();
                    }
                }
        );
 
        btnProximo.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onClickProximo();
                    }
                }
        );
 
        btnUltimo.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onClickUltimo();
                    }
                }
        );
    }
 
    private void onClickUltimo() {
        registroAtual = colaboradorList.size() - 1;
        getValores(registroAtual);
    }
 
    private void onClickProximo() {
        if (registroAtual != colaboradorList.size() - 1) {
            getValores(++registroAtual);
        }
    }
 
    private void onClickAnterior() {
        if (registroAtual != 0) {
            getValores(--registroAtual);
        }
    }
 
    private void onClickPrimeiro() {
        registroAtual = 0;
        getValores(registroAtual);
    }
 
    private void getValores(int index) {
        if (index <= colaboradorList.size() - 1) {
            Colaborador colaboradorAtual = colaboradorList.get(index);
            txtMat_colab.setText(colaboradorAtual.getMat_colab());
            txtNome.setText(colaboradorAtual.getNome());
            txtCargo.setText(colaboradorAtual.getCargo());
            txtId_centro_custo.setText(colaboradorAtual.getId_centro_custo());
        }
    }
 
    private void onClickAlterar() {
        ColaboradorController cc = new ColaboradorController();
        String mat_colab = colaboradorList.get(registroAtual).getMat_colab();
        try {
            cc.alterar(txtMat_colab.getText(), txtNome.getText(), txtCargo.getText(), txtId_centro_custo.getText());
            JOptionPane.showMessageDialog(this, "Colaborador alterado com sucesso!");
            clearFields();
            colaboradorList = new ColaboradorController().listaColaborador();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "Nao foi possivel alterar colaborador!\n" + e.getLocalizedMessage());
        } catch (ParseException e) {
			JOptionPane.showMessageDialog(this, "Tente novamente" + e.getLocalizedMessage());// TODO Auto-generated catch block
			e.printStackTrace();
		} 
    }
 
    private void onClickSalvar() {
        ColaboradorController cc = new ColaboradorController();
        try {
            cc.salvar(txtMat_colab.getText(), txtNome.getText(), txtCargo.getText(), txtId_centro_custo.getText());
            JOptionPane.showMessageDialog(this, "Colaborador salvo com sucesso!");
            clearFields();
            colaboradorList = new ColaboradorController().listaColaborador();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, 
                "Nao foi possivel salvar colaborador!\n" + 
                e.getLocalizedMessage()
            );
            e.printStackTrace();
        } catch (ParseException e) {
        	JOptionPane.showMessageDialog(this, "Tente novamente\n" + e.getLocalizedMessage());// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
 
    private void onClickExcluir() {
        ColaboradorController cc = new ColaboradorController();
        String mat_colab = colaboradorList.get(registroAtual).getMat_colab();
        try {
            cc.excluir(txtMat_colab.getText());
            JOptionPane.showMessageDialog(this, "Colaborador excluido com sucesso!");
            clearFields();
            colaboradorList = new ColaboradorController().listaColaborador();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, 
                "Nao foi possivel excluir o colaborador!n" + 
                e.getLocalizedMessage()
            );
        }
    }
 
    private void onClickLocalizar() {
        ColaboradorController cc = new ColaboradorController();
        try {
            Colaborador c = cc.buscaColaboradorPorNome(txtLocalizar.getText());
            txtMat_colab.setText(c.getMat_colab());
            txtNome.setText(c.getNome());
            txtCargo.setText(c.getCargo());
            txtId_centro_custo.setText(c.getId_centro_custo());
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, 
                "Ocorreu um erro, tente novamente!n" + 
                e.getLocalizedMessage()
            );
        } catch (NullPointerException e){
            JOptionPane.showMessageDialog(this, 
                "Colaborador não localizdo ou não existe!n" + 
                e.getLocalizedMessage()
            );
        }
    }
 
    private void clearFields() {
    	txtMat_colab.setText("");
    	txtNome.setText("");
        txtCargo.setText("");
        txtId_centro_custo.setText("");
        txtLocalizar.setText("");
    }
 
    public static void main(String[] args) {
        ColaboradorFrame frame = new ColaboradorFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

[/i]e aqui as outras classes:

package consultoria.controller;

import consultoria.dao.CentroDeCustoDao;
import consultoria.model.CentroDeCusto;
 


import javax.swing.*;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;

public class CentroDeCustoControlller {
    public void salvar(String codigo, String nome) 
            throws SQLException, ParseException 
        {
            CentroDeCusto centrodecusto = new CentroDeCusto();
            centrodecusto.setCodigo(codigo);
            centrodecusto.setNome_setor(nome);
     
            new CentroDeCustoDao().salvar(centrodecusto);
        }
     
        public void alterar(String codigo, String nome) 
            throws ParseException, SQLException 
        {
             
            CentroDeCusto centrodecusto = new CentroDeCusto();
            centrodecusto.setCodigo(codigo);
            centrodecusto.setNome_setor(nome);
     
            new CentroDeCustoDao().alterar(centrodecusto);
        }
     
        public List<CentroDeCusto> listaCentroDeCusto() {
            CentroDeCustoDao dao = new CentroDeCustoDao();
            try {
                return dao.findCentroDeCusto();
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(null, 
                    "Problemas ao localizar colaborador" + 
                    e.getLocalizedMessage()
                );
            }
            return null;
        }
     
        public void excluir(String codigo) throws SQLException {
            new CentroDeCustoDao().excluir(codigo);
        }    
     
        public CentroDeCusto buscaCentroDeCustoPorNome(String nome) throws SQLException {
            CentroDeCustoDao dao = new CentroDeCustoDao();
            return dao.findByName(nome);
        }
}
package consultoria.controller;

import consultoria.dao.ColaboradorDao;
import consultoria.model.Colaborador;
 


import javax.swing.*;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;

public class ColaboradorController {
    public void salvar(String mat_colab, String nome, String cargo, String id_centro_custo) 
            throws SQLException, ParseException 
        {
            Colaborador colaborador = new Colaborador();
            colaborador.setMat_colab(mat_colab);
            colaborador.setNome(nome);
            colaborador.setCargo(cargo);
            colaborador.setId_centro_custo(id_centro_custo);
     
            new ColaboradorDao().salvar(colaborador);
        }
     
        public void alterar(String mat_colab, String nome, String cargo, String id_centro_custo) 
            throws ParseException, SQLException 
        {
             
            Colaborador colaborador = new Colaborador();
            colaborador.setMat_colab(mat_colab);
            colaborador.setNome(nome);
            colaborador.setCargo(cargo);
            colaborador.setId_centro_custo(id_centro_custo);
     
            new ColaboradorDao().alterar(colaborador);
        }
     
        public List<Colaborador> listaColaborador() {
            ColaboradorDao dao = new ColaboradorDao();
            try {
                return dao.findColaboradores();
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(null, 
                    "Problemas ao localizar colaborador" + 
                    e.getLocalizedMessage()
                );
            }
            return null;
        }
     
        public void excluir(String mat_colab) throws SQLException {
            new ColaboradorDao().excluir(mat_colab);
        }    
     
        public Colaborador buscaColaboradorPorNome(String nome) throws SQLException {
            ColaboradorDao dao = new ColaboradorDao();
            return dao.findByName(nome);
        }
}
package consultoria.dao;

import consultoria.model.CentroDeCusto;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CentroDeCustoDao extends GenericDao{
    public void salvar(CentroDeCusto centrodecusto) throws SQLException {
        String insert = "INSERT INTO CENTRO_CUSTO(codigo, nome) VALUES(?,?)";
        save(insert, centrodecusto.getCodigo(), centrodecusto.getNome_setor());
    }
 
    public void alterar(CentroDeCusto centrodecusto) throws SQLException {
        String update = "UPDATE CENTRO_CUSTO " +
                "SET nome = ? " +
                "WHERE codigo = ?";
        update(update, centrodecusto.getCodigo(), centrodecusto.getNome_setor());
    }
 
    public void excluir(String codigo) throws SQLException {
        String delete = "DELETE FROM CENTRO_CUSTO WHERE codigo = ?";
        delete(delete, codigo);
    }
 
    public List<CentroDeCusto> findCentroDeCusto() throws SQLException {
        List<CentroDeCusto> centrosdecusto = new ArrayList<CentroDeCusto>();
 
        String select = "SELECT * FROM CENTRO_CUSTO";
 
        PreparedStatement stmt = 
            getConnection().prepareStatement(select);
             
        ResultSet rs = stmt.executeQuery();
 
        while (rs.next()) {
        	CentroDeCusto centrodecusto = new CentroDeCusto();
            centrodecusto.setCodigo(rs.getString("codigo"));
            centrodecusto.setNome_setor(rs.getString("nome"));
            centrosdecusto.add(centrodecusto);
        }
 
        rs.close();
        stmt.close();
 
        return centrosdecusto;
    }
 
    public CentroDeCusto findByName(String codigo) throws SQLException {
        String select = "SELECT * FROM CENTRO_CUSTO WHERE codigo = ?";
        CentroDeCusto centrodecusto = null;
        PreparedStatement stmt = 
            getConnection().prepareStatement(select);
             
        stmt.setString(1, codigo);
        ResultSet rs = stmt.executeQuery();
 
        while (rs.next()) {
            centrodecusto = new CentroDeCusto();
            centrodecusto.setCodigo(rs.getString("codigo"));
            centrodecusto.setNome_setor(rs.getString("nome"));
        }
 
        rs.close();
        stmt.close();
        return centrodecusto;
    }
    
}
package consultoria.dao;

import consultoria.model.Colaborador;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ColaboradorDao extends GenericDao{
    public void salvar(Colaborador colaborador) throws SQLException {
        String insert = "INSERT INTO COLABORADOR(mat_colab, nome, cargo, id_centro_custo) VALUES(?,?,?,?)";
        save(insert, colaborador.getMat_colab(), colaborador.getNome(), colaborador.getCargo(), colaborador.getId_centro_custo());
    }
 
    public void alterar(Colaborador colaborador) throws SQLException {
        String update = "UPDATE COLABORADOR " +
                "SET nome = ?, cargo = ?, id_centro_custo = ? " +
                "WHERE mat_colab = ?";
        update(update, colaborador.getMat_colab(), colaborador.getNome(), colaborador.getCargo(), colaborador.getId_centro_custo());
    }
 
    public void excluir(String mat_colab) throws SQLException {
        String delete = "DELETE FROM COLABORADOR WHERE mat_colab = ?";
        delete(delete, mat_colab);
    }
 
    public List<Colaborador> findColaboradores() throws SQLException {
        List<Colaborador> colaboradores = new ArrayList<Colaborador>();
 
        String select = "SELECT * FROM COLABORADOR";
 
        PreparedStatement stmt = 
            getConnection().prepareStatement(select);
             
        ResultSet rs = stmt.executeQuery();
 
        while (rs.next()) {
        	Colaborador colaborador = new Colaborador();
            colaborador.setMat_colab(rs.getString("mat_colab"));
            colaborador.setNome(rs.getString("nome"));
            colaborador.setCargo(rs.getString("cargo"));
            colaborador.setId_centro_custo(rs.getString("id_centro_custo"));
            colaboradores.add(colaborador);
        }
 
        rs.close();
        stmt.close();
 
        return colaboradores;
    }
 
    public Colaborador findByName(String nome) throws SQLException {
        String select = "SELECT * FROM COLABORADOR WHERE nome = ?";
        Colaborador colaborador = null;
        PreparedStatement stmt = 
            getConnection().prepareStatement(select);
             
        stmt.setString(1, nome);
        ResultSet rs = stmt.executeQuery();
 
        while (rs.next()) {
            colaborador = new Colaborador();
            colaborador.setMat_colab(rs.getString("mat_colab"));
            colaborador.setNome(rs.getString("nome"));
            colaborador.setCargo(rs.getString("cargo"));
            colaborador.setId_centro_custo(rs.getString("id_centro_custo"));
        }
 
        rs.close();
        stmt.close();
        return colaborador;
    }
    
}
package consultoria.dao;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConectionDataBase {
    private static final String URL_MYSQL = 
            "jdbc:mysql://localhost/Auditor";
             
        private static final String DRIVER_CLASS = 
            "com.mysql.jdbc.Driver";
             
        private static final String USER = "root";
         
        private static final String PASS = "";
     
        public static Connection getConnection() {
            System.out.println("Conectando ao Banco de Dados");
            try {
                Class.forName(DRIVER_CLASS);
                return DriverManager.getConnection(URL_MYSQL, USER, PASS);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            return null;
        }
}
package consultoria.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public abstract class GenericDao {
	private Connection connection;
	
	protected GenericDao(){
		this.connection = ConectionDataBase.getConnection();
	}
	
	protected Connection getConnection(){
		return connection;
	}
	
	protected void save(String insertSql, Object... parametros) throws
SQLException{
		PreparedStatement pstmt =
				getConnection().prepareStatement(insertSql);
		
		for (int i = 0; i < parametros.length; i++){
			pstmt.setObject(i+1, parametros[i]);
		}
		
		pstmt.execute();
		pstmt.close();
	}
	
	protected void update(String updateSql, Object id, Object...
parametros) throws SQLException{
		PreparedStatement pstmt =
				getConnection().prepareStatement(updateSql);
		
		for (int i = 0; i < parametros.length; i++){
			pstmt.setObject(i+1, parametros[i]);
		}
		pstmt.setObject(parametros.length + 1, id);
		pstmt.execute();
		pstmt.close();
	}
	
	protected void delete(String deleteSql, Object... parametros)
throws SQLException{
		PreparedStatement pstmt =
				getConnection().prepareStatement(deleteSql);
		
		for(int i = 0; i < parametros.length; i++){
			pstmt.setObject(i+1, parametros[i]);
		}
		
		pstmt.execute();
		pstmt.close();
	}
	
}
package consultoria.frame;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

@SuppressWarnings("serial")
public class AuditoriaMainFrame extends JFrame {

	private JPanel contentPane;

	/**
	 * Launch the application.
	 */

public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					AuditoriaMainFrame frame = new AuditoriaMainFrame();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */

	public AuditoriaMainFrame() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
	}

}
package consultoria.frame;

import consultoria.controller.CentroDeCustoControlller;
import consultoria.model.CentroDeCusto;
 
import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;

@SuppressWarnings("serial")
public class CentroCustoFrame extends JFrame {
    private JLabel lbCodigo, lbNome_setor;
    private JTextField txtCodigo, txtNome_setor, txtLocalizar; 

    private JButton btnSalvar, btnAlterar, btnExcluir, btnClear, btnLocalizar;
    private JButton btnPrimeiro, btnProximo, btnAnterior, btnUltimo;
 
    private List<CentroDeCusto> centrodecustoList = new 

CentroDeCustoControlller().listaCentroDeCusto();
    private int registroAtual = 0;
 
    public CentroCustoFrame() {
        super("CentroDeCusto");
        Container tela = getContentPane();
        getContentPane().setLayout(null);
        lbCodigo = new JLabel("Código com 5 digitos");
        lbNome_setor = new JLabel("Nome do setor");
 
        lbCodigo.setBounds(10,10,240,15);
        lbNome_setor.setBounds(10, 50, 240, 15);
 
        lbCodigo.setForeground(Color.BLACK);
        lbNome_setor.setForeground(Color.BLACK);
 
        lbCodigo.setFont(new Font("Courier New", Font.BOLD, 14));
        lbNome_setor.setFont(new Font("Courier New", Font.BOLD, 14));
 
        tela.add(lbCodigo);
        tela.add(lbNome_setor);
 
        txtCodigo = new JTextField();
        txtNome_setor = new JTextField();
 
        txtCodigo.setBounds(10, 25, 174, 20);
        txtNome_setor.setBounds(10, 65, 265, 20);
 
        tela.add(txtCodigo);
        tela.add(txtNome_setor);
 
        btnSalvar = new JButton("Salvar");
        btnAlterar = new JButton("Alterar");
        btnExcluir = new JButton("Excluir");
        btnClear = new JButton("Limpar");
        btnPrimeiro = new JButton("|<");
        btnAnterior = new JButton("<<");
        btnProximo = new JButton(">>");
        btnUltimo = new JButton(">|");
 
        btnSalvar.setBounds(10, 170, 80, 20);
        btnAlterar.setBounds(100, 170, 80, 20);
        btnExcluir.setBounds(190, 170, 80, 20);
 
        tela.add(btnSalvar);
        tela.add(btnAlterar);
        tela.add(btnExcluir);
 
        btnPrimeiro.setBounds(301, 25, 50, 20);
        btnAnterior.setBounds(301, 65, 50, 20);
        btnClear.setBounds(289, 96, 65, 20);
        btnProximo.setBounds(301, 127, 50, 20);
        btnUltimo.setBounds(301, 158, 50, 20);
 
        tela.add(btnPrimeiro);
        tela.add(btnAnterior);
        tela.add(btnClear);
        tela.add(btnProximo);
        tela.add(btnUltimo);
 
        JLabel lbLocalizar = new JLabel("Localizar por nome");
        lbLocalizar.setBounds(10, 96, 220, 20);
 
        txtLocalizar = new JTextField();
        txtLocalizar.setBounds(10, 116, 220, 20);
 
        btnLocalizar = new JButton("Ir");
        btnLocalizar.setBounds(236, 116, 55, 20);
 
        tela.add(lbLocalizar);
        tela.add(txtLocalizar);
        tela.add(btnLocalizar);
 
        setSize(380, 235);
        setVisible(true);
        setLocationRelativeTo(null);
 
        btnSalvar.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onClickSalvar();
                    }
                }
        );
 
        btnAlterar.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onClickAlterar();
                    }
                }
        );
 
        btnExcluir.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onClickExcluir();
                    }
                }
        );
 
        btnClear.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        clearFields();
                        registroAtual = 0;
                    }
                }
        );
 
        btnLocalizar.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onClickLocalizar();
                    }
                }
        );
 
        btnPrimeiro.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onClickPrimeiro();
                    }
                }
        );
        btnAnterior.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onClickAnterior();
                    }
                }
        );
 
        btnProximo.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onClickProximo();
                    }
                }
        );
 
        btnUltimo.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onClickUltimo();
                    }
                }
        );
    }
 
    private void onClickUltimo() {
        registroAtual = centrodecustoList.size() - 1;
        getValores(registroAtual);
    }
 
    private void onClickProximo() {
        if (registroAtual != centrodecustoList.size() - 1) {
            getValores(++registroAtual);
        }
    }
 
    private void onClickAnterior() {
        if (registroAtual != 0) {
            getValores(--registroAtual);
        }
    }
 
    private void onClickPrimeiro() {
        registroAtual = 0;
        getValores(registroAtual);
    }
 
    private void getValores(int index) {
        if (index <= centrodecustoList.size() - 1) {
            CentroDeCusto centrodecustoAtual = centrodecustoList.get(index);
            txtCodigo.setText(centrodecustoAtual.getCodigo());
            txtNome_setor.setText(centrodecustoAtual.getNome_setor());
        }
    }
 
    private void onClickAlterar() {
        CentroDeCustoControlller cc = new CentroDeCustoControlller();
        String codigo = centrodecustoList.get(registroAtual).getCodigo();
        try {
            cc.alterar(txtCodigo.getText(), txtNome_setor.getText());
            JOptionPane.showMessageDialog(this, "Colaborador alterado com sucesso!");
            clearFields();
            centrodecustoList = new CentroDeCustoControlller

().listaCentroDeCusto();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "Nao foi possivel alterar cadastro!n" + 
        e.getLocalizedMessage());
        } catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
    }
 
    private void onClickSalvar() {
        CentroDeCustoControlller cc = new CentroDeCustoControlller();
        try {
            cc.salvar(txtCodigo.getText(), txtNome_setor.getText());
            
            JOptionPane.showMessageDialog(this, "Centro de custo salvo com sucesso!");
            clearFields();
            centrodecustoList = new CentroDeCustoControlller().listaCentroDeCusto();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, 
                "Nao foi possivel salvar centro de custo!n" + 
                e.getLocalizedMessage());
            e.printStackTrace();
        } catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
 
    private void onClickExcluir() {
        CentroDeCustoControlller cc = new CentroDeCustoControlller();
        String codigo = centrodecustoList.get(registroAtual).getCodigo();
        try {
            cc.excluir(txtCodigo.getText());
            JOptionPane.showMessageDialog(this, "Centro de custo excluido com sucesso!");
            clearFields();
            centrodecustoList = new CentroDeCustoControlller

().listaCentroDeCusto();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, 
                "Nao foi possivel excluir o centro de custo!n" + 
                e.getLocalizedMessage()
            );
        }
    }
 
    private void onClickLocalizar() {
        CentroDeCustoControlller cc = new CentroDeCustoControlller();
        try {
            CentroDeCusto c = cc.buscaCentroDeCustoPorNome(txtLocalizar.getText());
            txtCodigo.setText(c.getCodigo());
            txtNome_setor.setText(c.getNome_setor());
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, 
                "Ocorreu um erro, tente novamente!n" + 
                e.getLocalizedMessage()
            );
        } catch (NullPointerException e){
            JOptionPane.showMessageDialog(this, 
                "Colaborador não localizdo ou não existe!n" + 
                e.getLocalizedMessage()
            );
        }
    }
 
    private void clearFields() {
    	txtCodigo.setText("");
    	txtNome_setor.setText("");
        txtLocalizar.setText("");
    }
 
    public static void main(String[] args) {
        ColaboradorFrame frame = new ColaboradorFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
package consultoria.model;

public class CentroDeCusto {
	private String codigo;
	private String nome_setor;

	public String getCodigo() {
		return codigo;
	}
	public void setCodigo(String codigo) {
		this.codigo = codigo;
	}
	public String getNome_setor() {
		return nome_setor;
	}
	public void setNome_setor(String nome_setor) {
		this.nome_setor = nome_setor;
	}

}
package consultoria.model;

public class Colaborador {
    private String mat_colab;
    private String nome;
    private String cargo;
    private String id_centro_custo;
    //gere os métodos getters and setters
	public String getMat_colab() {
		return mat_colab;
	}
	public void setMat_colab(String mat_colab) {
		this.mat_colab = mat_colab;
	}
	public String getNome() {
		return nome;
	}
	public void setNome(String nome) {
		this.nome = nome;
	}
	public String getCargo() {
		return cargo;
	}
	public void setCargo(String cargo) {
		this.cargo = cargo;
	}
	public String getId_centro_custo() {
		return id_centro_custo;
	}
	public void setId_centro_custo(String id_centro_custo) {
		this.id_centro_custo = id_centro_custo;
	}
	
	
}

3 Respostas

U

jhon1987 pelo que entendi você quer uma tela que faça o gerenciamento dos outros recursos (ex.: abrir alguns JFrames e finalizá-los)?

Se for isso é simples, cria um jframe principal e adiciona nele componentes gráficos na qual suas ações possam chamar as outras telas. Mantendo a instância do objeto você consegue finalizá-los.

J

oi, é exatamente isso que quero, mas ainda estou um pouco perdido no paradigma de orientaçao a objeto, estou engatinhando ainda. Se voce puder me da uma ajuda no código agradeço urbgames.

S

Olá amigo

você pode dar uma olhada em:

http://oswing.sourceforge.net/

já que está começando você poderia iniciar pelo demo10.

Boa sorte

Silvio Guedes

Criado 27 de setembro de 2014
Ultima resposta 6 de out. de 2014
Respostas 3
Participantes 3