Fórum Combobox Dinamicas [DUVIDA] #468181
28/01/2014
0
Bom galera sou novo em JAVA
E tenho essa duvida.. ao selecionar uma UF 'rs' quero que aparece na combobox municipio 'CANOAS'
ou seja somente o que foi cadastrado na tabela Municipios
estou com essa duvida se alguem puder me ajudar agradeco
// Evento que da ação a combobox UF
@Override
public void actionPerformed(ActionEvent euf) {
UFVO ufvo = (UFVO) view.getUfJComboBox().getSelectedItem();
// METODO TRY CATCH EM CASO DE EXECOES JUNTO COM A CONDIÇÃO if e else
// sendo assim se UF não for selecionado return mensagem
try {
view.getMunicipioJComboBox().removeAllItems();
if (view.getUfJComboBox().getSelectedItem() != null) {
CarregaObjetosnacombo(nome, ufvo);
} else {
JOptionPane.showMessageDialog(view, "UF não selecionada");
}
} catch (BairroException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(view, "erro1");
} catch (DataBaseException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(view, "erro2");
}
}
// metodo responsavel por carregar operacoes no evento Action performed da
// combobox
public void CarregaObjetosnacombo(CharSequence nome, UFVO ufvo)
throws BairroException, DataBaseException {
ResultSet rs = null;
PreparedStatement query = null;
Connection connection = null;
String sql = null;
try {
connection = DataSource.getConnection();
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/cliente-db", "impacta",
"impacta");
sql = "SELECT nm_municipio,id_municipio ,id_uf FROM municipio";
try {
query = connection.prepareStatement(sql);
rs = query.executeQuery();
query.setString(1, String.valueOf(rs.getString("id_uf")));
} catch (Exception e) {
}
List<Municipio> listMunicipios = new ArrayList<Municipio>();
List<UFVO> listUfvos = new ArrayList<UFVO>();
while (rs.next()) {
Municipio municipio = new Municipio();
//query.setString(1, String.valueOf(rs.getString("id_uf")));
municipio.setId(rs.getInt("id_municipio"));
municipio.setNome(rs.getString("nm_municipio"));
municipio.setUF(ufvo);
view.getUfJComboBox().addItem(ufvo.isSelecionado());
view.getMunicipioJComboBox().addItem(
rs.getString("nm_municipio"));
view.getMunicipioJComboBox().addItem(municipio.getUF());
listMunicipios.add(municipio);
listUfvos.add(ufvo);
if (ufvo.isSelecionado()) {
view.getMunicipioJComboBox().setModel(new DefaultComboBoxModel<>());
}
}
for (Municipio municipio : listMunicipios) {
System.out.println(municipio.getId());
System.out.println(view.getUfJComboBox());
/**if (view.getUfJComboBox().getSelectedItem().equals(municipio.getNome())) {
view.getMunicipioJComboBox().setSelectedItem(rs.getString("nm_municipio"));
}
if (ufvo.equals(municipio.getNome())) {
view.getMunicipioJComboBox().getSelectedIndex();
view.getMunicipioJComboBox().removeAllItems();
}
if (view.getMunicipioJComboBox().getSelectedItem().equals(ufvo)) {
view.getMunicipioJComboBox().removeAllItems();
}
if (view.getUfJComboBox().getSelectedIndex() > 0) {
}else if (view.getMunicipioJComboBox().getSelectedItem() == municipio.getNome()) {
view.getMunicipioJComboBox().removeAllItems();
}*/
}
} catch (SQLException cause) {
cause.printStackTrace();
JOptionPane.showMessageDialog(null, "Não foi possivel Carregar");
}
}
Felipe Rodrigues
Curtir tópico
+ 0Posts
29/01/2014
Henrique Gasparotto
Gostei + 0
29/01/2014
Felipe Rodrigues
// Evento que da ação a combobox UF
@Override
public void actionPerformed(ActionEvent euf) {
UFVO uf = (UFVO) view.getUfJComboBox().getSelectedItem();
try {
if (view.getUfJComboBox().getSelectedItem() != null) {
CarregaObjetosnacombo(uf);
}
} catch (BairroException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(view, "erro1");
} catch (DataBaseException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(view, "erro2");
}
}
// metodo responsavel por carregar operacoes no evento Action performed da
// combobox
public void CarregaObjetosnacombo(UFVO uf) throws BairroException,
DataBaseException {
List<Municipio> listMunicipios = new ArrayList<Municipio>();
ResultSet rs = null;
PreparedStatement query = null;
Connection connection = null;
String sql = null;
try {
connection = DataSource.getConnection();
sql = "SELECT nm_municipio,id_municipio,id_uf FROM municipio"
+ " WHERE id_uf = ? ORDER BY id_uf ";
System.out.println(sql);
try {
query = connection.prepareStatement(sql);
query.setString(1, String.valueOf(uf));
rs = query.executeQuery();
while (rs.next()) {
Municipio municipio = new Municipio();
municipio.setId(rs.getInt("id_municipio"));
municipio.setNome(rs.getString("nm_municipio"));
municipio.setUF(uf);
view.getMunicipioJComboBox().addItem(
rs.getString("nm_municipio"));
listMunicipios.add(municipio);
if (view.getMunicipioJComboBox().getSelectedIndex() >= 1) {
view.getMunicipioJComboBox().setSelectedIndex(0);
view.getMunicipioJComboBox().removeAllItems();
view.getMunicipioJComboBox().setSelectedItem(rs.next());
rs.next();
}
}
} catch (Exception cause) {
cause.printStackTrace();
JOptionPane.showMessageDialog(view,
" Não foi possivel carregar " + cause);
}
} catch (Exception cause) {
cause.printStackTrace();
JOptionPane
.showMessageDialog(view, "Não foi possivel fazer Select");
} finally {
DataSource.close(connection);
}
}
RESOLVIDO MEU AMIGO. MESMO ASSIM OBRIGADO
Gostei + 0
31/01/2014
Henrique Gasparotto
Gostei + 0
31/01/2014
Felipe Rodrigues
CARA EU ESTOU COM UMA DUVIDA AGORA. Tipo consegui fazer MInhas comboboX Se comunicarem. consegui listar no JTABLE Porém me resta uma unica duvida. VAMOS SUPER QUE NA ABA MUNICIPIOS EU CADASTRE A UF 'RS' Com nome do municipio canoas; DEPOIS CADASTRO A ULTIMA UF 'AP' com o nome de testre bom até ai blz quando vou para na aba BAIRROS. ele me mostra os municipios cadastrados para cada uF Porém na hora de cadastrar o Bairro acontes o Seguinte. Se eu selecionar a O municipio da UF' RS' que é canoas ele insere no bairro canoas; se eu selecionar o municipio da UF 'AP' ele cadastra no bairro canoas. e não no bairro AP Se alguem puder me ajudar ae agradeco qualquer coisa posto o codigos
Gostei + 0
03/02/2014
Henrique Gasparotto
Gostei + 0
03/02/2014
Felipe Rodrigues
Opa henrrique. obrigado pelo retorno... segue o codigo que faz o select .
Segue minha duvida mais detalhada.
Fala Galera Beleza??
Espero que sim.
Tentarei ser breve na minha ultima duvida referente a esse projeto.
Bom Estava com muitas duvidas mas o pessoal que tem força de vontade de ensinar e tal me ajudou e Muito.
Porém ainda falta algo
Tenho MENU CADASTRO DE MUNICIPIOS
Nela eu apenas cadastrei os Municipios DE SP E RS.
RS --> CANOAS
SP --> Suzano
Beleza até ai funcionando
Sendo assim.. Agora tenho meu MENU BAIRRO.
No bairro montei uma logica. na classe
BairroEscolherUFaction
que ao Selecionar uma UF na COMBOBOXUF
mostrará o resultado do municipio cadastrado na COMBOBOXmUNICIPIO
Sendo assim até ai bleza tudo funcionando.
PORÉM A DUVIDA.
Ná hora de gravar o registro está alternando..
Se eu quiser salvar por exempo Primeiro a UF de SP NO BAIRRO DE SP
Ao invés de Salvar em SP
Salva em RS.
Ou seja Não tem um parametro.
Preciso saber como fazer para salvar aonde preciso.
acredito que a causa disso seja meu While. meu loop no caso.
Postando A CLASSE.
caso alguem saiba Obrigado.
--------------------------------------
classe
// Evento que da ação a combobox UF
@Override
public void actionPerformed(ActionEvent euf) {
UFVO uf = (UFVO) view.getUfJComboBox().getSelectedItem();
Integer municipio = (Integer) view.getMunicipioJComboBox()
.getSelectedIndex();
try {
if (uf.isSelecionado()) {
CarregaObjetosnacombo(uf);
} else if (view.getMunicipioJComboBox().getSelectedIndex() != 1) {
view.CarregaBairro(municipio);
}
} catch (BairroException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(view, "erro1");
} catch (DataBaseException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(view, "erro2");
} catch (Exception e) {
e.printStackTrace();
}
}
// metodo responsavel por carregar operacoes no evento Action performed da
// combobox
public void CarregaObjetosnacombo(UFVO uf) throws BairroException,
DataBaseException {
List<Bairro> listBairros = new ArrayList<Bairro>();
ResultSet rs = null;
PreparedStatement query = null;
Connection connection = null;
String sql = null;
Bairro domain = null;
try {
connection = DataSource.getConnection();
sql = "SELECT nm_municipio FROM municipio " + "WHERE id_uf = ?";
System.out.println(sql);
try {
// Municipio domain2 = new Municipio();
query = connection.prepareStatement(sql);
query.setString(1, uf.toString());
rs = query.executeQuery();
if (view.getUfJComboBox().getSelectedItem() != null) {
rs.equals(domain);
rs.next();
domain = new Bairro();
domain.setMunicipio(new Municipio());
// domain.getMunicipio().setId(rs.getInt("id_municipio"));
domain.getMunicipio().setNome(rs.getString("nm_municipio"));
domain.getMunicipio().setUF(uf);
// view.getMunicipioJComboBox().setSelectedIndex(rs.getInt("id_municipio"));
view.getMunicipioJComboBox().addItem(
rs.getString("nm_municipio"));
listBairros.add(domain);
} else {
rs.first();
}
if (view.getMunicipioJComboBox().getSelectedItem() != null) {
rs.next();
}
} catch (Exception cause) {
cause.printStackTrace();
JOptionPane.showMessageDialog(view,
" Não foi possivel carregar " + cause);
}
} catch (Exception cause) {
cause.printStackTrace();
JOptionPane
.showMessageDialog(view, "Não foi possivel fazer Select");
} finally {
DataSource.close(connection);
}
}
public void limpaUF() {
final DefaultTableModel model;
model = (DefaultTableModel) view.getBairrosJTable().getModel();
model.getDataVector().clear();
view.getBairrosJTable().updateUI();
}
Gostei + 0
05/02/2014
Henrique Gasparotto
Cara, pelo que eu consegui observar tu não está percorrendo todo o ResultSet, está pegando somente o próximo da lista. O ideal é tu utilizar um foreach no try do método CarregaObjetosnacombo(), e dentro desse foreach comparar as UFs. Dá um olhada nessa parte e qualquer coisa é só avisar.
Gostei + 0
05/02/2014
Felipe Rodrigues
Entendi henrrique.. Vou tentar então fazer um foreach.
Gostei + 0
06/02/2014
Felipe Rodrigues
Fala henrrique.. mechi um pouco no codigo e consegui ajustar essa questão .. Porem..ainda me resta um erro.
como converter o id em String. para que possa salvar..
está assim o codigo e a Imgem está no final
public void CarregaObjetosnacombo() throws BairroException,
DataBaseException {
List<Bairro> listBairros = new ArrayList<Bairro>();
UFVO uf = (UFVO) view.getUfJComboBox().getSelectedItem();
try {
connection = DataSource.getConnection();
sql = "SELECT nm_municipio,id_municipio FROM municipio "
+ "WHERE id_uf = ?";
System.out.println(sql);
try {
// Municipio domain2 = new Municipio();
query = connection.prepareStatement(sql);
query.setString(1, uf.toString());
rs = query.executeQuery();
while (rs.next()) {
DefaultComboBoxModel<Object> model = new DefaultComboBoxModel<Object>();
view.getMunicipioJComboBox().setModel(model);
//Municipio municipio = (Municipio) model.getSelectedItem();
String municipios = (String) model.getSelectedItem();
//model.setSelectedItem(rs.getObject("id_municipio"));
model.addElement(rs.getObject("id_municipio"));
model.setSelectedItem(rs.getObject("nm_Municipio"));
//model.addElement(rs.getObject("nm_municipio"));
//model.setSelectedItem(rs.getObject("nm_municipio"));
domain = new Bairro();
domain.setMunicipio(new Municipio());
domain.getMunicipio().setNome(municipios);
domain.getMunicipio().setId(Integer.getInteger(municipios));
domain.getMunicipio().setUF(uf);
listBairros.add(domain);
}
} catch (Exception cause) {
cause.printStackTrace();
JOptionPane.showMessageDialog(view,
" Não foi possivel carregar " + cause);
}
} catch (Exception cause) {
cause.printStackTrace();
JOptionPane
.showMessageDialog(view, "Não foi possivel fazer Select");
} finally {
DataSource.close(connection);
}
}
[img]http://arquivo.devmedia.com.br/forum/imagem/356353-20140206-154734.png[/img]
Gostei + 0
09/02/2014
Henrique Gasparotto
Gostei + 0
10/02/2014
Felipe Rodrigues
Opa henrrique então.. preciso de um inteiro pelo seguinte fato. No banco será salvocomo int ..mas na combobox virá o nome do municipio que é um id entende? o problema só esta na hora de salvart
Gostei + 0
10/02/2014
Henrique Gasparotto
Gostei + 0
10/02/2014
Felipe Rodrigues
Então henrrique.. essa parte ai eu ja fiz e tal.. O problema é na hora de salvar.. A classe BairroOkAction.. é uma classe separada. ela só vai servir para salvar os Objetos em questão.. o problema é que assim.. Não consigo fazer com que ao salvar o Campo da combobox Municipio transforme de String para Integer. Pois no Banco de dados o id_municipio é do tipo Int. e na combobox está como String. é somente essa conversão que preciso para terminar o Projeto.. Se vc quiser te passo essas classes.
Gostei + 0
Clique aqui para fazer login e interagir na Comunidade :)