How do I get foreign key values in a JFrame form

0

I'm creating a form in JFrame to insert data into a table that contains two foreign keys (these keys are not automatically generated).

What do I have to put in the insert to get the foreign keys?

public void inserir(Tratamento tratamento) {
     try{
         try (Connection conexao = getConexao(); PreparedStatement stmt = conexao.prepareStatement("insert into tratamento "
                 + "(codigo_tratamento, titulo,  descricao) "
                 + "values (?,?,?)")) {
             stmt.setString(1, tratamento.getCodigo_tratamento());

             stmt.setString(2, tratamento.getTitulo());

             stmt.setString(3, tratamento.getDescricao());

             stmt.execute();
         }
    }catch(SQLException e){
    }
    //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
    
asked by anonymous 25.05.2014 / 16:47

1 answer

1

You can use a JComboBox . Where each item of ComboBox has a label and a value. You can use the id to make it easier to insert .

TofilltheJComboBox,itisenoughintheJFramecountertoloadthepossiblevaluesthroughaselectandthencreatetheItemsandaddthemtoComboBox.

Beinggeneric,thesimplestwouldbesomethinglike:

List<Entidade>entidades=EntidadeDAO.buscar();this.entidades=entidades;//VariáveldeinstânciadaclasseJComboBox<Entidade>combo=newJComboBox<Entidade>();this.combo=combo;for(Entidadeentidade:entidades){combo.addItem(entidade);//LabelqueseráexibidanatelaviradométodotoString()}

Somewherethatperformstheinsertaction:

Entidadeentidade=this.entidades.get(this.combo.getSelectedIndex());//ouEntidadeentidade=this.combo.getSelectedItem();IntegerforeignKey=entidade.getId();//Apartirdaivocêpodepassarachaveestrangeiraparaainserçãodaentidadetratamento.this.tratamentoDAO.inserir(tratamento,foreignKey,...);

Thiscodeisverygeneric,justadapttoyourprogrammingstyle.IfyouuseMVC,thereisthe ListCellRenderer that helps separate logic from view of logic controller , never used, but can be useful.

    
25.05.2014 / 19:32