4

I have a JTable created using a model, which is based on a matrix of objects. For each row, I want to put in a specific column (the 5th) some information using a JComboBox. I have tried the following:

for(int i=0; i < n ; i++) {  
    .....  
    data[i][5] = new JComboBox(aux); // aux is a Vector of elements I wanna insert  
}  
table.setModel(new MyTableModel()); // MyTableModel() already takes into consideration the data[][] object  

The problem is that data[i][5] = new JComboBox(aux); does not create a JComboBox object in that specific cell of the JTable, but pastes a code into the row. What can I do to solve this problem?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
anna-k
  • 117
  • 1
  • 1
  • 5
  • Does this answer your question? [How to add JComboBox to a specific cell in the JTable](https://stackoverflow.com/questions/3426175/how-to-add-jcombobox-to-a-specific-cell-in-the-jtable) – Richard Wave Nov 20 '20 at 09:32

4 Answers4

9

One way is to override the getCellEditor() method to return an appropriate editor. Here is an example to get you started:

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

public class TableComboBoxByRow extends JFrame
{
    List<TableCellEditor> editors = new ArrayList<TableCellEditor>(3);

    public TableComboBoxByRow()
    {
        // Create the editors to be used for each row

        String[] items1 = { "Red", "Blue", "Green" };
        JComboBox comboBox1 = new JComboBox( items1 );
        DefaultCellEditor dce1 = new DefaultCellEditor( comboBox1 );
        editors.add( dce1 );

        String[] items2 = { "Circle", "Square", "Triangle" };
        JComboBox comboBox2 = new JComboBox( items2 );
        DefaultCellEditor dce2 = new DefaultCellEditor( comboBox2 );
        editors.add( dce2 );

        String[] items3 = { "Apple", "Orange", "Banana" };
        JComboBox comboBox3 = new JComboBox( items3 );
        DefaultCellEditor dce3 = new DefaultCellEditor( comboBox3 );
        editors.add( dce3 );

        //  Create the table with default data

        Object[][] data =
        {
            {"Color", "Red"},
            {"Shape", "Square"},
            {"Fruit", "Banana"},
            {"Plain", "Text"}
        };
        String[] columnNames = {"Type","Value"};
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        JTable table = new JTable(model)
        {
            //  Determine editor to be used by row
            public TableCellEditor getCellEditor(int row, int column)
            {
                int modelColumn = convertColumnIndexToModel( column );

                if (modelColumn == 1 && row < 3)
                    return editors.get(row);
                else
                    return super.getCellEditor(row, column);
            }
        };
        System.out.println(table.getCellEditor());

        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
    }

    public static void main(String[] args)
    {
        TableComboBoxByRow frame = new TableComboBoxByRow();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible(true);
    }
}

Edit: code updated to use trashgod's suggestion.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Very succinct. As an alternative, consider `List editors = new ArrayList(3)`. – trashgod Jul 15 '10 at 15:27
  • Yes, I wrote the example code before generics existed. I guess I should update it to be more current :) – camickr Jul 15 '10 at 18:08
  • On reflection, `List editors = new ArrayList(3)` may be better. It's more general, obviates the cast in `getCellEditor()` and allows the implementation to be changed. Sorry for the bum steer; still learning. – trashgod Jul 16 '10 at 03:36
2

Try something like this:

 public void example(){  

      TableColumn tmpColum =table.getColumnModel().getColumn(1);
      String[] DATA = { "Data 1", "Data 2", "Data 3", "Data 4" };
      JComboBox comboBox = new JComboBox(DATA);

      DefaultCellEditor defaultCellEditor=new DefaultCellEditor(comboBox);
      tmpColum.setCellEditor(defaultCellEditor);
      tmpColum.setCellRenderer(new CheckBoxCellRenderer(comboBox));
      table.repaint();
   }


/**
   Custom class for adding elements in the JComboBox.
*/
class CheckBoxCellRenderer implements TableCellRenderer {
        JComboBox combo;
        public CheckBoxCellRenderer(JComboBox comboBox) {
            this.combo = new JComboBox();
            for (int i=0; i<comboBox.getItemCount(); i++){
                combo.addItem(comboBox.getItemAt(i));
            }
        }
        public Component getTableCellRendererComponent(JTable jtable, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            combo.setSelectedItem(value);
            return combo;
        }
    }
Adrian
  • 655
  • 6
  • 10
  • This changes all cells in `tmpColum` into JComboBoxes. What if you only want to change a specific cell using its row and column? – Jesse James Mar 23 '20 at 15:17
1

For the JComboBox to be disaplyed, you have to use a TableCellRenderer. Take a look at Using a Combo Box as an Editor.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Riduidel
  • 22,052
  • 14
  • 85
  • 185
1

Hehe, it's not to be used like you proposed.

You have to create a custom TableCellRenderer or TableCellEditor. Then you can specify for which class it will be used:

JTable.setDefaultRenderer(Class<?> columnClass, TableCellRenderer renderer)
JTable.setDefaultEditor(Class<?> columnClass, TableCellEditor editor)

A detailed description can be found here: http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/components/table.html#combobox

For a custom renderer in a specific row & column, you can simply use:

final int specialRow = 1;
final int specialColumn = 5;

JTable table = new JTable(myModel) {
   private TableCellEditor mySpecialCellEditor = new SpecialCellEditor( ... );

   public TableCellEditor getCellEditor(int row, int column) {
      int modelColumn = convertColumnIndexToModel(column);
      int modelRow = convertRowIndexToModel(row);
      if (modelColumn == specialColumn && row == specialRow ) {
         return mySpecialCellEditor;
      } else {
         return super.getCellEditor(row, column);
      }
   }
};
Javaguru
  • 890
  • 5
  • 10
  • Thank you I have been analysing all these examples you posted and others,on the internet.. but they dont fit. I just need to create a JComboBox on a Specific place in the JTable, such as data[1][5] . The box is already created,I just need to link it on that place. In these examples I see they get a full column and create a JComboBox out of it, and I see nowhere how would they refer to a specific place in the table, such as row-2, column-5...etc... Thanks – anna-k Jul 15 '10 at 14:26