Can I do something like this? Or will the asynchronous nature of swing updates make it possible for this to be a bug? In other words, can I rely on the selected index being updated before I read it, or is it possible that it's not updated before I write to the database?
button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
combobox.addItem("New item");
combobox.setSelectedIndex(combobox.getItemCount()-1);
// write index to database
CellUtil.getCell(row,column).setCellValue(combobox.getSelectedIndex());
}
});
I just thought that I guess ActionListener is running in the same UI thread, so it should be updated just fine, right?
Or will the asynchronous nature of swing updates make it possible for this to be a bug?
You seem to be a bit fuzzy about how Swing and the AWT work. That will indeed make it hard to write Swing applications.
The AWT, including Swing, features an (one) event-dispatch thread. It is on the EDT that AWT / Swing performs all rendering and event dispatch. That makes these activities asynchronous with respect to an application's initial thread, but they are all synchronous with respect to each other.
Generally speaking, AWT and Swing components are not inherently thread safe, so yes, it is entirely possible to create data races involving them, but you don't need to worry about that if your interactions with those components are limited to the EDT, including rendering and event handling activity. Except where specified otherwise, the methods of Swing and AWT components are synchronous with respect to the thread in which they are invoked.
Thus, the code presented in the question doesn't raise any particular thread safety concerns by itself. JComboBox.setSelectedIndex() updates the model of the target combo box synchronously, so, barring a data race from some other source, a getSelectedIndex() invoked subsequently in the same event handler will definitely observe the updated state.