Popular combobox inside jtable with database, how to proceed?

Asked

Viewed 365 times

0

Currently I populate a normal combobox this way:

this.CadperfilLinha.removeAllItems();
try {
    Class.forName(Auxiliar.AcessoBanco.getDriver());
    Connection con = DriverManager.getConnection(Auxiliar.AcessoBanco.getUrl(), Auxiliar.AcessoBanco.getUser(), Auxiliar.AcessoBanco.getPass());;
    Statement Sent = con.createStatement();
    ResultSet rs = Sent.executeQuery("Select * from Linha");
    CadperfilLinha.addItem("Selecione...");
    while (rs.next()) {
        this.CadperfilLinha.addItem(rs.getString("LINHA"));
    }
} catch (Exception e) {
    JOptionPane.showMessageDialog(null, e);
}

But now I’m needing to popular one inside the jtable, but I’m not getting it. I have it mounted here pulling only typed values inside the code and wanted it to use the database. Someone can give me a hand?

String[] values = new String[]{"Ativo", "Desativado"};

TableColumn col = jTable1.getColumnModel().getColumn(2);
col.setCellEditor(new MyComboBoxEditor(values));
col.setCellRenderer(new MyComboBoxRenderer(values));

class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {

    public MyComboBoxRenderer(String[] items) {
        super(items);
    }

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
            boolean hasFocus, int row, int column) {
        if (isSelected) {
            setForeground(table.getSelectionForeground());
            super.setBackground(table.getSelectionBackground());
        } else {
            setForeground(table.getForeground());
            setBackground(table.getBackground());
        }
        setSelectedItem(value);
        return this;
    }
}

class MyComboBoxEditor extends DefaultCellEditor {

    public MyComboBoxEditor(String[] items) {
        super(new JComboBox(items));
    }
}
  • Provide a [mcve] so that it is possible to simulate the problem and propose a solution

1 answer

3


If you need to popular a JComboBox with database data and want to isolate this fill, the best I can recommend is to create a ComboBoxModel and fill out the bank on his builder. a Comboboxmodel is nothing more than a template to fill a Jcombobox, when you create a combo and do combo.addItem(), what actually happens is the filling of a standard internal model created for the component, this standard model is the class DefaultComboBoxModel.

An example of how to create could be as below:

class MeuComboModel extends DefaultComboBoxModel {

    private ArrayList<String> itens;
    private Object itemSelected;

    public MeuComboModel() {
        this.itens = new ArrayList<>();
        this.itens.add("Option 1");
        this.itens.add("Option 2");
        this.itens.add("Option 3");
        this.itens.add("Option 4");
    }

    @Override
    public int getSize() {
        return itens.size();
    }

    @Override
    public Object getElementAt(int index) {
        return itens.get(index);
    }

    @Override
    public void setSelectedItem(Object anItem) {
        this.itemSelected = anItem;

    }

    @Override
    public Object getSelectedItem() {
        return this.itemSelected;
    }
}

I created a class inheriting from DefaultComboBoxModelso we need to set up as little as possible. In this case I am directly populating, but just assign the items coming from the bank in the list instead.

To assign the model to the combo, you can either start already passing an instance of it or set later through the method setModel():

  • Method 1 :

    JComboBox combo = new JComboBox(new MeuComboModel());
    
  • Method 2:

    seucombo.setModel(new MeuComboModel());
    

Until now, the combo is already filled, and if the items are Strings or some primitive type of java, depending on the model your table uses, just pass this combo to an instance of the class DefaultTableCellEditor:

this.table.getColumnModel().getColumn(<<indice da coluna>>).setCellEditor(new DefaultCellEditor(comboBox));

With this, the combo is displayed correctly when its cell goes into edit mode, the option selected as well, as can be seen below:

inserir a descrição da imagem aqui

If you want to read more about it, I recommend the official documentation tutorials: How to Use Tables and How to Use Combo Boxes.

  • Thanks for the @Articuno example, that’s just what I needed. I’m just not knowing popular it with the same database information I do in the above example. I searched on youtube, on the net and couldn’t find an example of popular it itself. you could help me with this part?

  • I did it in a way that is wrong that was to use an existing combobox to pull his items with the code that you gave me.

  • there is a way this combo is visible and if the person passes tab or enter it to choose an option?

  • @Lucas16 if you provide a [mcve] I can try to help.

  • problem q I use the netbeans table itself. to make an example I will take a while. but as you said yourself "With this, the combo is displayed correctly when his cell goes into edit mode, the option selected as well, as can be seen below:" I wish q it already appeared and q while going through it force a choice.

  • @Lucas16 if you do not provide one [mcve] there is no way I can help you. Posting generic response makes it broad and I can be negative (and rightly so) so.

  • @Lucas16 access the link, read and try to learn how to create an example. This will help you not only to participate in the site, but to program better, as a [mcve] is a way to isolate many problems in codes and almost always helps us to find the problems themselves.

  • okay, thank you...

  • @Lucas16 but the answer answered the question, you know you can accept it ne?

  • Okay, I guess that’s it.

  • @Lucas16 the netbeans has a code tab. I recommend that as you move around the interface, take a look at what’s going on in the code as well. It is important to know how to do the same things that the graphic constructor does, otherwise you will face these kinds of problems throughout your development. To tell you the truth, I don’t even recommend this constructor, it creates unnecessary and complicated code, in a Wikipedia it is possible to do the same things with much less line of code and much simpler than this netbeans graphics editor.

  • You could type the generic, it’s more readable

  • What do you mean? I don’t understand.

Show 9 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.