[RESOLVIDO] Problemas com instanciação de objetos

2 respostas
victorrgds

fala galera, blz?

Vamos direto ao assunto…estou tendo o seguinte problema com essa classe:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;

   public class EfetuarLocaView extends JFrame{
   
      protected JButton consultarCliente, efetuarLocacao, consultarVeiculo;
  		protected JTable tabelaPF,tabelaPJ, tabelaVeiculo;
		protected JScrollPane resultadoPF,resultadoPJ;    
		protected JPanel painel;
		protected TableModel modelPF, modelPJ;
		protected JComboBox tipoTarifa;	
		protected int idLocacao;
		
		JLabel localLocacao,  dtLocacao, tipTarifa;
		JTextField tf_buscaCli, tf_buscaVeic, tf_localLocacao, tf_dtLocacao;
		JRadioButton radioPF, radioPJ;
   
      public EfetuarLocaView(){
      
         super("Locar Veículo");
         setSize(540,540);
         setLocation(400,100);
         painel = new JPanel(new SpringLayout());
         SpringLayout layout = new SpringLayout();
         painel.setLayout(layout);
      
         
			//JLabel
			localLocacao = new JLabel("Local de locação");
			dtLocacao = new JLabel("Data de locação");
			tipTarifa = new JLabel("Tipo da tarifa");
			
			//JText
			tf_buscaCli = new JTextField(15);
			tf_buscaVeic = new JTextField(15);
			tf_localLocacao = new JTextField(15);
			tf_dtLocacao = new JTextField(15);
			
			//JRadio
			
    	  	radioPF = new JRadioButton("CPF");
    	  	radioPJ = new JRadioButton("CNPJ");
		  
		  	//Grupo de Opcoes
    	  	ButtonGroup grupo = new ButtonGroup();
    	  	grupo.add(radioPF);
        	grupo.add(radioPJ);
		  	radioPF.setSelected(true);

				
			//JButtons
			consultarCliente = new JButton("Consultar Cliente");
         consultarVeiculo = new JButton("Consultar Veículo");
         efetuarLocacao = new JButton("Efetuar Locação");
      
			//Tratador dos botoes
			TrataBotao tratador = new TrataBotao();
			
			//Ação dos botões
			consultarCliente.addActionListener(tratador);
			consultarVeiculo.addActionListener(tratador);
			efetuarLocacao.addActionListener(tratador);
			
			//JCombo de tarifa
		   String[] opcoes ={"Km rodado", "Km livre"};
		   tipoTarifa = new JComboBox(opcoes);
		   tipoTarifa.setSelectedIndex(0);
			
      
   		//tabelas
			tabelaPF = new JTable();
			tabelaPJ = new JTable();
		
			modelPF = new DefaultTableModel(new String[] {"ID", "CPF", "Nome"},0);
			modelPJ = new DefaultTableModel(new String[] {"ID", "CNPJ", "Nome"},0);
		
			tabelaPF.setModel(modelPF);
			tabelaPJ.setModel(modelPJ);
		
			resultadoPF = new JScrollPane();
			resultadoPF.setViewportView(tabelaPF);
		
			resultadoPJ = new JScrollPane();
			resultadoPJ.setViewportView(tabelaPJ);
		
			tabelaPF.setPreferredScrollableViewportSize(new Dimension(490, 100));
			tabelaPJ.setPreferredScrollableViewportSize(new Dimension(490, 100));   	
			
			//Instancia Tabela
         tabelaVeiculo = new JTable();
      //Define um model2o para a tabela com o Título da coluna
         TableModel model2 = new DefaultTableModel(new String[] {"Veiculo","Grupo","Acessórios","Placa"},0);
      //seta o model2o
         tabelaVeiculo.setModel(model2);
      //seta o nome??
         tabelaVeiculo.setName("Resultado");
      //nao sei ainda
         JScrollPane resultado2 = new JScrollPane();
      //nao sei ainda
         resultado2.setViewportView(tabelaVeiculo);
      //define um tamanho fixo pra tabela
         tabelaVeiculo.setPreferredScrollableViewportSize(new Dimension(490, 100));
      //nao sei	
         DefaultTableModel dtm2 = (DefaultTableModel) tabelaVeiculo.getModel();
      //adiciona uma linha
         dtm2.addRow(new Object[] {"912311","Gol","Paula Tejano","10/09/2012"});
      
         painel.add(consultarVeiculo);
         painel.add(consultarCliente);
         painel.add(resultado2);
         painel.add(resultadoPF);
			painel.add(resultadoPJ);
         painel.add(efetuarLocacao);
			painel.add(tf_buscaCli);
			painel.add(tf_buscaVeic);
			painel.add(radioPF);
			painel.add(radioPJ);
			painel.add(localLocacao);
			painel.add(tf_localLocacao);
			painel.add(dtLocacao);
			painel.add(tf_dtLocacao);
			painel.add(tipoTarifa);
			painel.add(tipoTarifa);
      
  		//Configura a posição de cada item na tela - Radio CPF
         layout.putConstraint(SpringLayout.WEST, radioPF,20,SpringLayout.WEST, painel);
         layout.putConstraint(SpringLayout.NORTH, radioPF,20,SpringLayout.NORTH, painel);
			
		//Configura a posição de cada item na tela - Radio CNPJ
         layout.putConstraint(SpringLayout.WEST, radioPJ,0,SpringLayout.WEST, radioPF);
         layout.putConstraint(SpringLayout.NORTH, radioPJ,20,SpringLayout.NORTH, radioPF);
      
		//Configura a posição de cada item na tela - Text Cliente
         layout.putConstraint(SpringLayout.WEST, tf_buscaCli,100,SpringLayout.WEST, radioPF);
         layout.putConstraint(SpringLayout.NORTH, tf_buscaCli,10,SpringLayout.NORTH, radioPF);
			
		//Configura a posição de cada item na tela - Botao Consultar Cliente
         layout.putConstraint(SpringLayout.WEST, consultarCliente,205,SpringLayout.WEST, tf_buscaCli);
         layout.putConstraint(SpringLayout.NORTH, consultarCliente,0,SpringLayout.NORTH, tf_buscaCli);
      
      //Configura a posição de cada item na tela - tabela cliente
         layout.putConstraint(SpringLayout.WEST, resultadoPF,17,SpringLayout.WEST, painel);
         layout.putConstraint(SpringLayout.NORTH, resultadoPF,40,SpringLayout.NORTH, consultarCliente);
		
		//Configura a posição de cada item na tela - tabela cliente
         layout.putConstraint(SpringLayout.WEST, resultadoPJ,17,SpringLayout.WEST, painel);
         layout.putConstraint(SpringLayout.NORTH, resultadoPJ,40,SpringLayout.NORTH, consultarCliente);
		
		
		//Configura a posição de cada item na tela - Text Veiculo
         layout.putConstraint(SpringLayout.WEST, tf_buscaVeic,0,SpringLayout.WEST, tf_buscaCli);
         layout.putConstraint(SpringLayout.NORTH, tf_buscaVeic,140,SpringLayout.NORTH, resultadoPJ);
      
      //Configura a posição de cada item na tela - botao Consultar Veiculo
         layout.putConstraint(SpringLayout.WEST, consultarVeiculo,205,SpringLayout.WEST, tf_buscaVeic);
         layout.putConstraint(SpringLayout.NORTH, consultarVeiculo,0,SpringLayout.NORTH, tf_buscaVeic);
      
      //Configura a posição de cada item na tela - tabela veiculo
         layout.putConstraint(SpringLayout.WEST, resultado2,17,SpringLayout.WEST, painel);
         layout.putConstraint(SpringLayout.NORTH, resultado2,40,SpringLayout.NORTH, tf_buscaVeic);
      
      //Configura a posição de cada item na tela - botao efetuar locação
         layout.putConstraint(SpringLayout.WEST, efetuarLocacao,205,SpringLayout.WEST, painel);
         layout.putConstraint(SpringLayout.NORTH, efetuarLocacao,210,SpringLayout.NORTH, resultado2);
		
		//JLabels + JText
			layout.putConstraint(SpringLayout.WEST, localLocacao,17,SpringLayout.WEST, painel);
         layout.putConstraint(SpringLayout.NORTH, localLocacao,140,SpringLayout.NORTH, resultado2);
			
			layout.putConstraint(SpringLayout.WEST, tf_localLocacao,17,SpringLayout.WEST, painel);
         layout.putConstraint(SpringLayout.NORTH, tf_localLocacao,160,SpringLayout.NORTH, resultado2);
			
			layout.putConstraint(SpringLayout.WEST, dtLocacao,200,SpringLayout.WEST, painel);
         layout.putConstraint(SpringLayout.NORTH, dtLocacao,140,SpringLayout.NORTH, resultado2);
			
			layout.putConstraint(SpringLayout.WEST, tf_dtLocacao,200,SpringLayout.WEST, painel);
         layout.putConstraint(SpringLayout.NORTH, tf_dtLocacao,160,SpringLayout.NORTH, resultado2);
			
		//Configura posição do JCombo
			layout.putConstraint(SpringLayout.WEST, tipoTarifa,380,SpringLayout.WEST, painel);
         layout.putConstraint(SpringLayout.NORTH, tipoTarifa,160,SpringLayout.NORTH, resultado2);	
			
			//Configura posição do JCombo
			layout.putConstraint(SpringLayout.WEST, tipTarifa,380,SpringLayout.WEST, painel);
         layout.putConstraint(SpringLayout.NORTH, tipTarifa,140,SpringLayout.NORTH, resultado2);	
 
         setResizable(false);
         painel.setOpaque(true);
         setContentPane(painel);
         setVisible(true);
      
     		//Fecha apenas a janela que esta aberta
         fechaJanela  fecha = new fechaJanela();
      		
      
      }
    
   
	
private class TrataBotao implements ActionListener  
{  
   public void actionPerformed(ActionEvent evento)
	{ 
		//botao consultar cliente
		ClienteCtrl ctrl = new ClienteCtrl();
		Iterator<ClientePJ> itPJ;
		Iterator<ClientePF> itPF;
		//List<ClientePJ> retornoPJ;
		//List<ClientePF> retornoPF;
		DefaultTableModel dtmPJ;
		DefaultTableModel dtmPF;
		

			//radioPF
			if(evento.getSource()==radioPF){
				resultadoPF.setVisible(true);
				resultadoPJ.setVisible(false);
				painel.repaint();
			
			}
			//radioPJ
			if(evento.getSource()==radioPJ){
				resultadoPJ.setVisible(true);
				resultadoPF.setVisible(false);
				painel.repaint();
				
			}

	
		if(evento.getSource()==consultarCliente)
		{
				
			if(radioPF.isSelected())
			{
				List<ClientePF> retornoPF = ctrl.consultarPF(tf_buscaCli.getText());;
				dtmPF = (DefaultTableModel) tabelaPF.getModel();
					
				// antes de preencher, limpa todos os dados do JTable, remove linhas em branco da tabela
				while (tabelaPF.getRowCount() > 0) {
					dtmPF.removeRow(0);
				}
					
				for (itPF = retornoPF.iterator(); itPF.hasNext();) {
					ctrl.cliPF = itPF.next();
					// inclui uma linha no JTable com os dados de um
					// registro retornado
					//
					dtmPF.addRow(new Object[] { ctrl.cliPF.getIdCliente(), ctrl.cliPF.getCPF(),  ctrl.cliPF.getNome()});
				}
		
				if(radioPJ.isSelected())
				{
					List<ClientePJ> retornoPJ = ctrl.consultarPJ(tf_buscaCli.getText());
					dtmPJ = (DefaultTableModel) tabelaPJ.getModel();
					
				// antes de preencher, limpa todos os dados do JTable, remove linhas em branco da tabela
				while (tabelaPJ.getRowCount() > 0) {
					dtmPJ.removeRow(0);
				}
					
				for (itPJ = retornoPJ.iterator(); itPJ.hasNext();) 
				{
					ctrl.cliPJ = itPJ.next();
					// inclui uma linha no JTable com os dados de um
					// registro retornado
					//
					dtmPJ.addRow(new Object[] { ctrl.cliPJ.getIdCliente(), ctrl.cliPJ.getCNPJ(),ctrl.cliPJ.getRazaoSocial()});
				}
			}


		}
	}
  
      
   //botao pesquisar  
   if(evento.getSource()==consultarVeiculo){  
                
   	Veiculos veiculos = new Veiculos();  
 		//List<Veiculos> retorno = veiculos.consultarVeiculos();  
      List<Veiculos> retorno = veiculos.consultarVeiculos(tf_buscaVeic.getText());   
      DefaultTableModel dtm = (DefaultTableModel) tabelaVeiculo.getModel();  
                      
      // antes de preencher, limpa todos os dados do JTable, remove linhas em branco da tabela  
      while (tabelaVeiculo.getRowCount() > 0) {  
      	dtm.removeRow(0);  
      }  
                      
      for (Iterator<Veiculos> it = retorno.iterator(); it.hasNext();) {  
      	veiculos = it.next();  
         // inclui uma linha no JTable com os dados de um  
         // registro retornado  
         //  
         dtm.addRow(new Object[] { veiculos.getNome(), veiculos.getGrupo(), veiculos.getPlaca()});  
      }  
   }  
      

		//Cadastrar locacao
		if(evento.getSource()==efetuarLocacao){
			LocacaoCtrl controle = new LocacaoCtrl();
					
			if(controle.cadastrarLocacao(tf_localLocacao.getText(),tf_dtLocacao.getText(),
			tipoTarifa.getSelectedItem().toString()))
				{
					JTextField texts[] ={tf_localLocacao,tf_dtLocacao};
					JOptionPane.showMessageDialog(null,Validar.textIsNull(texts));
				}
			}	
				
		}		

}
}
EfetuarLocaView.java:309: error: method cadastrarLocacao in class LocacaoCtrl cannot be applied to given types;
			if(controle.cadastrarLocacao(tf_localLocacao.getText(),tf_dtLocacao.getText(),
			           ^
  required: String,String,String,int
  found: String,String,String

Aqui vão as outras classes que estão ligadas a essa interface:

import javax.swing.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class Locacao
{
	protected String dtLocacao, /*grupoVeic,*/ localLocacao, tipoTarifa;
	protected int idLocacao;
	protected LocacaoDAO locacaoDAO = new LocacaoDAO();
	protected ClienteCtrl cliCtrl = new ClienteCtrl();
	protected Veiculos veiculos = new Veiculos();
	
	public Locacao()
	{
		setDtLocacao(this.dtLocacao);
		//setGrupoVeic(this.grupoVeic);
		setLocalLocacao(this.localLocacao);
		setTipoTarifa(this.tipoTarifa);
		setIdLocacao(idLocacao);
		locacaoDAO = new LocacaoDAO();
	}
	
	public Locacao(String dtLocacao, /*String grupoVeic,*/ String localLocacao, String tipoTarifa, int idLocacao)
	{
		setDtLocacao(dtLocacao);
		//setGrupoVeic(grupoVeic);
		setLocalLocacao(localLocacao);
		setTipoTarifa(tipoTarifa);
		setIdLocacao(idLocacao);
	}
	
	public String getDtLocacao()
	{
		return dtLocacao;
	}
	
	public void setDtLocacao(String dtLocacao)
	{
		this.dtLocacao = dtLocacao;
	}
	
	/*public String getGrupoVeic()
	{
		return grupoVeic;
	}
	
	public void setGrupoVeic(String grupoVeic)
	{
		this.grupoVeic = grupoVeic;
	}*/
	
	public String getLocalLocacao()
	{
		return localLocacao;
	}
	
	public void setLocalLocacao(String localLocacao)
	{
		this.localLocacao = localLocacao;
	}
	
	public String getTipoTarifa()
	{
		return tipoTarifa;
	}
	
	public void setTipoTarifa(String tipoTarifa)
	{
		this.tipoTarifa = tipoTarifa;
	}
	
	public void setIdLocacao(int idLocacao)
	{
		this.idLocacao = idLocacao;
	}
	
	public int getIdLocacao()
	{
		return idLocacao;
	}
	
	public void cadastrarLocacao(Locacao cadLocacao)
	{
		locacaoDAO.incluir(cadLocacao);	
	}


}

Controle:

import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;


public class LocacaoCtrl
{
	Locacao cadLocacao = new Locacao();
	
	
	public LocacaoCtrl(){
	
	}
	
	public boolean cadastrarLocacao(String dtLocacao, /*String grupoVeic,*/ String localLocacao, String tipoTarifa, int idLocacao){
		try{
				cadLocacao = new Locacao(dtLocacao, /*grupoVeic,*/ localLocacao, tipoTarifa, idLocacao);
				cadLocacao.cadastrarLocacao(cadLocacao);
				cadSucess(true);
				return true; 
			}
			catch(Exception e1){
			
				cadSucess(false);
				return false; 
			}
		

	}	
	
	//retorna a msg de cadastrado com sucesso
	public void cadSucess(boolean cad){
		if(cad)JOptionPane.showMessageDialog(null,"Locação efetuada com sucesso");
		else JOptionPane.showMessageDialog(null,"Locação não efetuada! Verifique os dados!");
	}	
	
}

E dao:

import javax.swing.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class LocacaoDAO
{
	public LocacaoDAO(){
	
	}
	
	public void incluir(Locacao loca)
	{
		String sqlInsert = "INSERT INTO locacao(idLocacao, dataLocacao, grupoVeiculo, localLocacao, tipoTarifa) VALUES (?, ?, ?, ?, ?)";
		
		Connection conn = null;
		PreparedStatement stm = null;
		try {
			
			AcessoBD bd = new AcessoBD();
			conn = bd.obtemConexao();
			
			//
			// Inclusao dos dados na tabela VEICULO
			//
			stm = conn.prepareStatement(sqlInsert);

			stm.setString(1, loca.getDtLocacao());
			//stm.setString(2, loca.getGrupoVeic());
			stm.setString(2, loca.getLocalLocacao());
			stm.setString(3, loca.getTipoTarifa());
			stm.execute();


		} catch (Exception e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				System.out.print(e1.getStackTrace());
			}
		} finally {
			if (stm != null) {
				try {
					stm.close();
				} catch (SQLException e1) {
					System.out.print(e1.getStackTrace());
				}
			}
		}
		//conn.commit();
	}	
	
	//Pesquisa veiculos
	
	public List<Veiculos> pesquisar(String buscaText) {
		
		ArrayList resultadoPesquisa = new ArrayList<Veiculos>();
		
		String sqlSelect = "SELECT * FROM veiculo WHERE nome LIKE '%"+buscaText+"%'";
		PreparedStatement stm = null;
		ResultSet rs = null;
		Connection conn = null;
		
		try {
			AcessoBD bd = new AcessoBD();
			conn = bd.obtemConexao();
			
			stm = conn.prepareStatement(sqlSelect);

			rs = stm.executeQuery();

			while (rs.next()) {
				Veiculos rsc = new Veiculos(
						rs.getInt("idVeiculo"),
						rs.getString("nome"),
						rs.getString("grupo"),
						rs.getString("modelo"),
						rs.getString("placa"),
						rs.getString("chassi"),
						rs.getString("ar"),
						rs.getString("cadeira"),
						rs.getString("gps"));
						resultadoPesquisa.add(rsc);
			}
			return resultadoPesquisa;
			
		} catch (Exception e) {
			e.printStackTrace();
			return resultadoPesquisa;
			
		} finally {
			if (stm != null) {
				try {
					stm.close();
				} catch (SQLException e1) {
					System.out.print(e1.getStackTrace());
				}
			}
		  }
	
	}
	
	public List<ClientePF> pesquisarCli(String buscaText) {
		
		ArrayList resultadoPesquisa = new ArrayList<ClientePF>();
		
		String sqlSelect = "SELECT * FROM clientepf WHERE cpf LIKE '%"+buscaText+"%'";

		PreparedStatement stm = null;
		ResultSet rs = null;
		Connection conn = null;
		
		try{
			AcessoBD bd = new AcessoBD();
			conn = bd.obtemConexao();
			
			stm = conn.prepareStatement(sqlSelect);

			rs = stm.executeQuery();

			while (rs.next()) {
				ClientePF rsc = new ClientePF(
						rs.getString(3),
						rs.getString(5),
						rs.getString(3),
						rs.getString(7),
						rs.getString(10),
						rs.getString(9),
						rs.getString(8),
						rs.getString(12),
						rs.getInt("idCliente"),
						rs.getString(2),
						rs.getString(11),
						rs.getString(5));
				rsc.setIdCliente(rs.getInt("idCliente"));
				resultadoPesquisa.add(rsc);
			}
			return resultadoPesquisa;
			
		} catch (Exception e) {
			e.printStackTrace();
			return resultadoPesquisa;
			
		} finally {
			if (stm != null) {
				try {
					stm.close();
				} catch (SQLException e1) {
					System.out.print(e1.getStackTrace());
				}
			}
		}
	}
	
	public List<ClientePJ> pesquisarPJ(String buscaText) {
		
		ArrayList resultadoPesquisa = new ArrayList<ClientePJ>();
	
		String sqlSelect =  "SELECT * FROM clientepj where cnpj LIKE '%"+buscaText+"%'";

		PreparedStatement stm = null;
		ResultSet rs = null;
		Connection conn = null;
		
		try {
			AcessoBD bd = new AcessoBD();
			conn = bd.obtemConexao();
			
			stm = conn.prepareStatement(sqlSelect);

			rs = stm.executeQuery();

			while (rs.next()) {
				ClientePJ rsc = new ClientePJ(
						rs.getString(3),
						rs.getString(4),
						rs.getString(5),
						rs.getString(7),
						rs.getString(8),
						rs.getString(9),
						rs.getString(10),
						rs.getString(11),
						rs.getInt(12),
						rs.getString(1),
						rs.getString(2),
						rs.getString(6));
						

				resultadoPesquisa.add(rsc);
			}
			return resultadoPesquisa;
			
		} catch (Exception e) {
			e.printStackTrace();
			return resultadoPesquisa;
			
		} finally {
			if (stm != null) {
				try {
					stm.close();
				} catch (SQLException e1) {
					System.out.print(e1.getStackTrace());
				}
			}
		}
	}


}

Eu sei oque esse erro representa, porém já fucei e não to conseguindo corrigir…

detalhe: estava funcionando, ai fui modificar e não salvei uma de segurança e deu nisso…

o idLocacao é AutoIncrement no bd(não sei se a informação é útil).

Abs,

2 Respostas

M

Olhe a assinatura desse método em LocacaoCtrl:

public boolean cadastrarLocacao(String dtLocacao, /*String grupoVeic,*/ String localLocacao, String tipoTarifa, int idLocacao){  
    try{  
        cadLocacao = new Locacao(dtLocacao, /*grupoVeic,*/ localLocacao, tipoTarifa, idLocacao);  
        cadLocacao.cadastrarLocacao(cadLocacao);  
        cadSucess(true);  
        return true;   
    } catch(Exception e1){  
        cadSucess(false);  
        return false;   
    }  
}

E olhe os parâmetros que você esta passando para ele aqui:

if(controle.cadastrarLocacao(tf_localLocacao.getText(),tf_dtLocacao.getText(), tipoTarifa.getSelectedItem().toString())) {  
    JTextField texts[] ={tf_localLocacao,tf_dtLocacao};
    JOptionPane.showMessageDialog(null,Validar.textIsNull(texts));  
}

Não deveria existir mais um parâmetro int no final desse método?

Té mais.

victorrgds

sim, na vdd é um valor definido ja…tipo “1”…logo depois de postar eu consegui dnv…rsrs

abs

Criado 15 de outubro de 2012
Ultima resposta 15 de out. de 2012
Respostas 2
Participantes 2