Is it possible to have the dropdown in each row be different, based on a column value for that row?
Yes, there are a number of different ways to do it. Here’s one:
In configureCell:
from javax.swing import JComboBox
# define the options for the comboboxes
options1 = ['OFF', 'Hand', 'Auto']
options2 = ['OFF', 'ON']
data = {}
if colName == 'col3':
# get the value to determine what combobox to show
col1 = self.data.getValueAt(rowIndex,1)
# create the combobox
if col1 == 'Options1':
options = options1
else:
options = options2
index = options.index(value)
# create the combobox
cb = JComboBox(options)
cb.setSelectedIndex(index)
data['renderer'] = cb
return data
In configureEditor:
from javax.swing import AbstractCellEditor,JComboBox, JTextField
from javax.swing.table import TableCellEditor
from java.awt.event import ItemListener, ItemEvent
# define the options for the comboboxes
options1 = ['OFF', 'Hand', 'Auto']
options2 = ['OFF', 'ON']
# used to listen to item change events in the combobox
class MyItemListener(ItemListener):
# Constructor
def __init__(self, table, value, rowIndex, colIndex):
self.table = table
self.rowIndex = rowIndex
self.colIndex = colIndex
self.value = value
optionType = self.table.data.getValueAt(rowIndex, 1)
if optionType == 'Options1':
self.options = options1
else:
self.options = options2
# this is fired when the combobox changes
def itemStateChanged(self, event):
if (event.getStateChange() == ItemEvent.SELECTED):
newValue = event.getItem()
# create a new dataset with the updated value
newDS = system.dataset.setValue(self.table.data, self.rowIndex, self.colIndex, newValue)
# write back to the source property
# update this to whereever your master data is
self.data = newDS
class myTableCellEditor(TableCellEditor, AbstractCellEditor):
def __init__(self, tableComponent):
self.table = tableComponent
self.editor = None
self.options = None
def getTableCellEditorComponent(self, table, value, isSelected, rowIndex, colIndex):
col1 = self.table.data.getValueAt(rowIndex,1)
# defind the options for the drop down
if col1 == 'Options1':
self.options = options1
else:
self.options = options2
# create a combo box with the options
self.editor = JComboBox(self.options)
index = self.options.index(value)
self.editor.setSelectedIndex(index)
# add an Item changed listener
self.editor.addItemListener(MyItemListener(self.table, value, rowIndex, colIndex))
return self.editor
def getCellEditorValue(self):
# is the editor a combobox?
if type(self.editor) is JComboBox:
# get the combobox value
newValue = self.editor.getSelectedItem()
# convert back to the options value
#newValue = self.options[selectedValue]
else:
# get the text field value
newValue = self.editor.getText()
return newValue
if colName == "col3":
m = myTableCellEditor(self)
return {"editor":m}
In onCellEdited:
if colName == 'col3':
self.data = system.dataset.setValue(self.data, rowIndex, colIndex, newValue)
This uses a column type of String that is set to Editable.
1 Like