Basically I want to know how to get access to JCombobox functions from JTable at a specific row. If anyone could help me to understand how to set for example first row (only first row - the other rows must not be affected and keep its functional) of the table in its combobox column to select item at index 0 (which is "Item 1").
This is the code that I currently have:
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class ComboboxColumnDemo {
static JFrame frame;
static JTable table;
public static void main(String[] args) {
createFrameAndTable();
// Resize to avoid error which makes it invisible.
frame.resize(500, 600);
// Turn a column into a combobox
makeColumnToBeACombobox(1);
}
public static void createFrameAndTable() {
// Create frame
frame = new JFrame();
frame.setSize(500, 500);
frame.setTitle("Demo program");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); // Set frame in the middle of the screen
frame.setVisible(true);
// Create table
table = new JTable();
table.setModel(new DefaultTableModel(
// Create rows
new Object[][] { { null, null, null }, { null, null, null }, },
// Create headers
new String[] { "Time", "Address", "Comment" })
{
//Set columns to be editable or uneditable
boolean[] columnEditables = new boolean[] { false, true, false };
//No idea what it does but it probably needs to be here
public boolean isCellEditable(int row, int column) {
return columnEditables[column];
}
});
// Create JScrollPane and table to it
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(table);
// Add JScrollPane with table to the frame
frame.add(scrollPane);
}
/**
* This method makes a column to be a combobox
*/
public static void makeColumnToBeACombobox(int whichColumn) {
JComboBox<String> combobox = new JComboBox<String>();
// Add items to JComboBox
combobox.addItem("Item 1");
combobox.addItem("Item 2");
combobox.addItem("Item 3");
// Make column to be a JComboBox column
table.getColumnModel().getColumn(whichColumn).setCellEditor(new DefaultCellEditor(combobox));
}
}