JComboBox, JTable, cellRendering CHALLENGE

Hi all,
I would like to ask a question of the resident guru concerning a Netbeans/MYSQL application. I based it on a tutorial found here: [http://www.netbeans.org/kb/61/java/gui-db-custom.html].
I have two seperate JDialogs that write data to a master table. One of the JDialogs is called "Customer Editor" and it contains various text fields bound to cells on the masterTable, no big deal.
Also in the "Customer Editor" JDialog there is a JComboBox that has a list of four values to choose from which are "Good", "Standby", "Failed", and "Complete".
I would like the data selected from the JComboBox to color itself when it writes to the JTable row/cell on the masterTable. For example if the user selects "Good" from the list, in the masterTable the font color of the String will be GREEN. Similarly, if the user selects "Failed" from the JComboBox I would like the String to return RED...following on "Standby" - BLUE, "Complete" - no color change.
Question: How do I write code that allows me to change the color of text in a cell when it comes from a JComboBox list?
If anyone out there picks up this thread, I will of course supply the code I have so far. I won't do it now as I am not sure even where the code should go. I think it would go in the source code for the masterTable view but I am not certain.
Any Java masters out there?
David

Thanks for the reply. I have been writing different cell renderers to get it working. Where should the code reside?
This is my operations view class. Should it be in here.
/CODE/
package operationsrecords;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import org.jdesktop.application.Task;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.RollbackException;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.jdesktop.beansbinding.AbstractBindingListener;
import org.jdesktop.beansbinding.Binding;
import org.jdesktop.beansbinding.PropertyStateEvent;
* The application's main frame.
public class OperationsRecordsView extends FrameView {
public OperationsRecordsView(SingleFrameApplication app) {
super(app);
initComponents();
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
     messageTimer = new Timer(messageTimeout, new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusMessageLabel.setText("");
     messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
} else if ("message".equals(propertyName)) {
String text = (String)(evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer)(evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
// tracking table selection
masterTable.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
firePropertyChange("recordSelected", !isRecordSelected(), isRecordSelected());
detailTable.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
firePropertyChange("detailRecordSelected", !isDetailRecordSelected(), isDetailRecordSelected());
// tracking changes to save
bindingGroup.addBindingListener(new AbstractBindingListener() {
@Override
public void targetChanged(Binding binding, PropertyStateEvent event) {
// save action observes saveNeeded property
setSaveNeeded(true);
// have a transaction started
entityManager.getTransaction().begin();
public boolean isSaveNeeded() {
return saveNeeded;
private void setSaveNeeded(boolean saveNeeded) {
if (saveNeeded != this.saveNeeded) {
this.saveNeeded = saveNeeded;
firePropertyChange("saveNeeded", !saveNeeded, saveNeeded);
public boolean isRecordSelected() {
return masterTable.getSelectedRow() != -1;
public boolean isDetailRecordSelected() {
return detailTable.getSelectedRow() != -1;
@Action
public void newRecord() {
operationsrecords.Customers c = new operationsrecords.Customers();
entityManager.persist(c);
list.add(c);
int row = masterTable.getRowCount() - 1;
masterTable.setRowSelectionInterval(row, row);
masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
setSaveNeeded(true);
JFrame mainFrame = OperationsRecordsApp.getApplication().getMainFrame();
CustomerEditor ce = new CustomerEditor(mainFrame, false);
ce.setCurrentRecord(c);
ce.setVisible(true);
if (ce.isCustomerConfirmed()) {
save().run();
} else {
refresh().run();
@Action(enabledProperty = "recordSelected")
public void deleteRecord() {
Object[] options = {"OK", "Cancel"};
int n = JOptionPane.showConfirmDialog(null, "Delete the records permanently?", "Warning",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null);
if (n == JOptionPane.YES_OPTION) {
int[] selected = masterTable.getSelectedRows();
List<operationsrecords.Customers> toRemove = new ArrayList<operationsrecords.Customers>(selected.length);
for (int idx = 0; idx < selected.length; idx++) {
operationsrecords.Customers c = list.get(masterTable.convertRowIndexToModel(selected[idx]));
toRemove.add(c);
entityManager.remove(c);
list.removeAll(toRemove);
save().run();
} else {
refresh().run();
@Action(enabledProperty = "recordSelected")
public void newDetailRecord() {
int index = masterTable.getSelectedRow();
operationsrecords.Customers c = list.get(masterTable.convertRowIndexToModel(index));
Collection<operationsrecords.Orders> os = c.getOrdersCollection();
if (os == null) {
os = new LinkedList<operationsrecords.Orders>();
c.setOrdersCollection(os);
operationsrecords.Orders o = new operationsrecords.Orders();
o.setShipDate(new java.util.Date());
entityManager.persist(o);
o.setCustomerId(c);
os.add(o);
masterTable.clearSelection();
masterTable.setRowSelectionInterval(index, index);
int row = os.size()-1;
detailTable.setRowSelectionInterval(row, row);
detailTable.scrollRectToVisible(detailTable.getCellRect(row, 0, true));
setSaveNeeded(true);
JFrame mainFrame = OperationsRecordsApp.getApplication().getMainFrame();
OrderEditor oe = new OrderEditor(mainFrame, false);
oe.setCurrentOrderRecord(o);
oe.setVisible(true);
if (oe.isOrderConfirmed()) {
save().run();
} else {
refresh().run();
@Action(enabledProperty = "detailRecordSelected")
public void deleteDetailRecord() {
Object[] options = {"OK", "Cancel"};
int n = JOptionPane.showConfirmDialog(null, "Delete the records permanently?", "Warning",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null);
if (n == JOptionPane.YES_OPTION) {
int index = masterTable.getSelectedRow();
operationsrecords.Customers c = list.get(masterTable.convertRowIndexToModel(index));
Collection<operationsrecords.Orders> os = c.getOrdersCollection();
int[] selected = detailTable.getSelectedRows();
List<operationsrecords.Orders> toRemove = new ArrayList<operationsrecords.Orders>(selected.length);
for (int idx = 0; idx < selected.length; idx++) {
selected[idx] = detailTable.convertRowIndexToModel(selected[idx]);
int count = 0;
Iterator<operationsrecords.Orders> iter = os.iterator();
while (count++ < selected[idx]) {
iter.next();
operationsrecords.Orders o = iter.next();
toRemove.add(o);
entityManager.remove(o);
os.removeAll(toRemove);
masterTable.clearSelection();
masterTable.setRowSelectionInterval(index, index);
list.removeAll(toRemove);
save().run();
} else {
refresh().run();
@Action(enabledProperty = "saveNeeded")
public Task save() {
return new SaveTask(getApplication());
private class SaveTask extends Task {
SaveTask(org.jdesktop.application.Application app) {
super(app);
@Override protected Void doInBackground() {
try {
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
} catch (RollbackException rex) {
rex.printStackTrace();
entityManager.getTransaction().begin();
List<operationsrecords.Customers> merged = new ArrayList<operationsrecords.Customers>(list.size());
for (operationsrecords.Customers c : list) {
merged.add(entityManager.merge(c));
list.clear();
list.addAll(merged);
return null;
@Override protected void finished() {
setSaveNeeded(false);
* An example action method showing how to create asynchronous tasks
* (running on background) and how to show their progress. Note the
* artificial 'Thread.sleep' calls making the task long enough to see the
* progress visualization - remove the sleeps for real application.
@Action
public Task refresh() {
return new RefreshTask(getApplication());
private class RefreshTask extends Task {
RefreshTask(org.jdesktop.application.Application app) {
super(app);
@SuppressWarnings("unchecked")
@Override protected Void doInBackground() {
setProgress(0, 0, 4);
setMessage("Rolling back the current changes...");
setProgress(1, 0, 4);
entityManager.getTransaction().rollback();
setProgress(2, 0, 4);
setMessage("Starting a new transaction...");
entityManager.getTransaction().begin();
setProgress(3, 0, 4);
setMessage("Fetching new data...");
java.util.Collection data = query.getResultList();
for (Object entity : data) {
entityManager.refresh(entity);
setProgress(4, 0, 4);
list.clear();
list.addAll(data);
return null;
@Override protected void finished() {
setMessage("Done.");
setSaveNeeded(false);
@Action
public void showAboutBox() {
if (aboutBox == null) {
JFrame mainFrame = OperationsRecordsApp.getApplication().getMainFrame();
aboutBox = new OperationsRecordsAboutBox(mainFrame);
aboutBox.setLocationRelativeTo(mainFrame);
OperationsRecordsApp.getApplication().show(aboutBox);
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
mainPanel = new javax.swing.JPanel();
masterScrollPane = new javax.swing.JScrollPane();
masterTable = new javax.swing.JTable();
newButton = new javax.swing.JButton();
deleteButton = new javax.swing.JButton();
detailScrollPane = new javax.swing.JScrollPane();
detailTable = new javax.swing.JTable();
deleteDetailButton = new javax.swing.JButton();
newDetailButton = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
menuBar = new javax.swing.JMenuBar();
javax.swing.JMenu fileMenu = new javax.swing.JMenu();
javax.swing.JMenuItem newRecordMenuItem = new javax.swing.JMenuItem();
javax.swing.JMenuItem deleteRecordMenuItem = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JSeparator();
javax.swing.JMenuItem saveMenuItem = new javax.swing.JMenuItem();
javax.swing.JMenuItem refreshMenuItem = new javax.swing.JMenuItem();
jSeparator2 = new javax.swing.JSeparator();
javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
javax.swing.JMenu helpMenu = new javax.swing.JMenu();
javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
statusPanel = new javax.swing.JPanel();
javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
statusMessageLabel = new javax.swing.JLabel();
statusAnimationLabel = new javax.swing.JLabel();
progressBar = new javax.swing.JProgressBar();
entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("OperationsRecordsPU").createEntityManager();
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(operationsrecords.OperationsRecordsApp.class).getContext().getResourceMap(OperationsRecordsView.class);
query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery(resourceMap.getString("query.query")); // NOI18N
list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
rowSorterToStringConverter1 = new operationsrecords.RowSorterToStringConverter();
mainPanel.setBackground(resourceMap.getColor("mainPanel.background")); // NOI18N
mainPanel.setName("mainPanel"); // NOI18N
masterScrollPane.setName("masterScrollPane"); // NOI18N
masterTable.setBackground(resourceMap.getColor("masterTable.background")); // NOI18N
masterTable.setGridColor(resourceMap.getColor("masterTable.gridColor")); // NOI18N
masterTable.setName("masterTable"); // NOI18N
masterTable.setShowVerticalLines(false);
org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${jobId}"));
columnBinding.setColumnName("Job Id");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${statusId.status}"));
columnBinding.setColumnName("Status Id.status");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${company}"));
columnBinding.setColumnName("Company");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${rig}"));
columnBinding.setColumnName("Rig");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${well}"));
columnBinding.setColumnName("Well");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${county}"));
columnBinding.setColumnName("County");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${state}"));
columnBinding.setColumnName("State");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${companyMan}"));
columnBinding.setColumnName("Company Man");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${phone}"));
columnBinding.setColumnName("Phone");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fax}"));
columnBinding.setColumnName("Fax");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${emailAddress}"));
columnBinding.setColumnName("Email Address");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
bindingGroup.addBinding(jTableBinding);
jTableBinding.bind();
masterScrollPane.setViewportView(masterTable);
masterTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("masterTable.columnModel.title0")); // NOI18N
masterTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("masterTable.columnModel.title1")); // NOI18N
masterTable.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("masterTable.columnModel.title2")); // NOI18N
masterTable.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("masterTable.columnModel.title3")); // NOI18N
masterTable.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("masterTable.columnModel.title4")); // NOI18N
masterTable.getColumnModel().getColumn(5).setHeaderValue(resourceMap.getString("masterTable.columnModel.title5")); // NOI18N
masterTable.getColumnModel().getColumn(6).setHeaderValue(resourceMap.getString("masterTable.columnModel.title6")); // NOI18N
masterTable.getColumnModel().getColumn(7).setHeaderValue(resourceMap.getString("masterTable.columnModel.title7")); // NOI18N
masterTable.getColumnModel().getColumn(8).setHeaderValue(resourceMap.getString("masterTable.columnModel.title8")); // NOI18N
masterTable.getColumnModel().getColumn(9).setHeaderValue(resourceMap.getString("masterTable.columnModel.title9")); // NOI18N
masterTable.getColumnModel().getColumn(10).setHeaderValue(resourceMap.getString("masterTable.columnModel.title10")); // NOI18N
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(operationsrecords.OperationsRecordsApp.class).getContext().getActionMap(OperationsRecordsView.class, this);
newButton.setAction(actionMap.get("newRecord")); // NOI18N
newButton.setBackground(resourceMap.getColor("newButton.background")); // NOI18N
newButton.setName("newButton"); // NOI18N
deleteButton.setAction(actionMap.get("deleteRecord")); // NOI18N
deleteButton.setBackground(resourceMap.getColor("jButton1.background")); // NOI18N
deleteButton.setName("deleteButton"); // NOI18N
detailScrollPane.setName("detailScrollPane"); // NOI18N
detailTable.setGridColor(resourceMap.getColor("detailTable.gridColor")); // NOI18N
detailTable.setName("detailTable"); // NOI18N
detailTable.setShowVerticalLines(false);
detailTable.getTableHeader().setReorderingAllowed(false);
org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${selectedElement.ordersCollection}");
jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, eLProperty, detailTable);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${shipDate}"));
columnBinding.setColumnName("Ship Date");
columnBinding.setColumnClass(java.util.Date.class);
columnBinding.setEditable(false);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${tool}"));
columnBinding.setColumnName("Tool");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${collar}"));
columnBinding.setColumnName("Collar");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${xo}"));
columnBinding.setColumnName("Xo");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${xo2}"));
columnBinding.setColumnName("Xo2");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${surfaceKit}"));
columnBinding.setColumnName("Surface Kit");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${comments}"));
columnBinding.setColumnName("Comments");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${directions}"));
columnBinding.setColumnName("Directions");
columnBinding.setColumnClass(String.class);
columnBinding.setEditable(false);
jTableBinding.setSourceUnreadableValue(java.util.Collections.emptyList());
bindingGroup.addBinding(jTableBinding);
jTableBinding.bind();
detailScrollPane.setViewportView(detailTable);
detailTable.getColumnModel().getColumn(0).setResizable(false);
detailTable.getColumnModel().getColumn(0).setPreferredWidth(10);
detailTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("detailTable.columnModel.title0")); // NOI18N
detailTable.getColumnModel().getColumn(1).setResizable(false);
detailTable.getColumnModel().getColumn(1).setPreferredWidth(5);
detailTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("detailTable.columnModel.title1")); // NOI18N
detailTable.getColumnModel().getColumn(2).setResizable(false);
detailTable.getColumnModel().getColumn(2).setPreferredWidth(5);
detailTable.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("detailTable.columnModel.title2")); // NOI18N
detailTable.getColumnModel().getColumn(3).setResizable(false);
detailTable.getColumnModel().getColumn(3).setPreferredWidth(5);
detailTable.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("detailTable.columnModel.title3")); // NOI18N
detailTable.getColumnModel().getColumn(4).setResizable(false);
detailTable.getColumnModel().getColumn(4).setPreferredWidth(5);
detailTable.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("detailTable.columnModel.title4")); // NOI18N
detailTable.getColumnModel().getColumn(5).setResizable(false);
detailTable.getColumnModel().getColumn(5).setPreferredWidth(5);
detailTable.getColumnModel().getColumn(5).setHeaderValue(resourceMap.getString("detailTable.columnModel.title5")); // NOI18N
detailTable.getColumnModel().getColumn(6).setResizable(false);
detailTable.getColumnModel().getColumn(6).setPreferredWidth(300);
detailTable.getColumnModel().getColumn(6).setHeaderValue(resourceMap.getString("detailTable.columnModel.title6")); // NOI18N
detailTable.getColumnModel().getColumn(7).setResizable(false);
detailTable.getColumnModel().getColumn(7).setPreferredWidth(300);
detailTable.getColumnModel().getColumn(7).setHeaderValue(resourceMap.getString("detailTable.columnModel.title7")); // NOI18N
deleteDetailButton.setAction(actionMap.get("deleteDetailRecord")); // NOI18N
deleteDetailButton.setBackground(resourceMap.getColor("jButton1.background")); // NOI18N
deleteDetailButton.setName("deleteDetailButton"); // NOI18N
newDetailButton.setAction(actionMap.get("newDetailRecord")); // NOI18N
newDetailButton.setBackground(resourceMap.getColor("jButton1.background")); // NOI18N
newDetailButton.setName("newDetailButton"); // NOI18N
jButton1.setAction(actionMap.get("editCustomer")); // NOI18N
jButton1.setBackground(resourceMap.getColor("jButton1.background")); // NOI18N
jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
jButton1.setName("jButton1"); // NOI18N
jButton2.setAction(actionMap.get("editOrder")); // NOI18N
jButton2.setBackground(resourceMap.getColor("jButton1.background")); // NOI18N
jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
jButton2.setName("jButton2"); // NOI18N
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
jTextField1.setName("jTextField1"); // NOI18N
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${rowSorter}"), jTextField1, org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setConverter(rowSorterToStringConverter1);
bindingGroup.addBinding(binding);
jLabel2.setIcon(resourceMap.getIcon("jLabel2.icon")); // NOI18N
jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
jLabel2.setName("jLabel2"); // NOI18N
javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(detailScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 1057, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
.addComponent(newDetailButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(deleteDetailButton))
.addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT

Similar Messages

  • Help with JComboBox-JTable

    Hi there!
    I'll try to explain my problem the best I can, I hope you can understand me so you may get to help me, I'd really appreciate it. I'm trying to make a JTable to render a cell as a JComboBox, that's ok and it's working fine. The problem comes when I try to change the combo value. The itemStateChanged method is supposed to get some values from a database, if the first is bigger than the second it shows an alert, else it makes an update to the database. Now, the problem is that, if the combobox default value is blank (""), it works fine, but if it's filled with something as a name ("anything") it automatically shows the alert, even if I'm not changing the combo value. The second problem is that it shows the alert twice, I'll try to explain with code:
    class Cambia_Cita extends javax.swing.AbstractCellEditor implements javax.swing.table.TableCellEditor ,java.awt.event.ItemListener{
        protected EventListenerList listenerList = new EventListenerList();
        protected ChangeEvent changeEvent = new ChangeEvent(this);   
        protected javax.swing.JComboBox combo = new javax.swing.JComboBox();
        int i;
        String valor = "";
        int j;
        javax.swing.JTable tabla = new javax.swing.JTable();
        public Cambia_Cita() {
            super();
            combo.addItemListener(this);
            Base base = new Base();
            Statement sta = base.conectar();
            try {
                ResultSet rs = sta.executeQuery("SELECT DISTINCT Nombre_Completo FROM Pacientes WHERE Alta = 'n'");
                combo.addItem("");
                while(rs.next())
                    combo.addItem(rs.getString("Nombre_Completo"));
            }catch(SQLException e) {
                System.out.println (e.getMessage());
            } finally {
                base.cerrar(sta);
            combo.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    System.out.println("algo");
                    tabla.setValueAt(valor,i,j);
        public Object getCellEditorValue() {
            return(combo.getSelectedItem());
        public java.awt.Component getTableCellEditorComponent(javax.swing.JTable table, Object value, boolean isSelected, int row, int column) {
            i = row;
            j = column;
            tabla = table;
            valor = value.toString();
            combo.setSelectedItem(tabla.getValueAt(i,j));
            System.out.println (i + "," + j);
            java.awt.Component c = table.getDefaultRenderer(String.class).getTableCellRendererComponent(table, value, isSelected, false, row, column);
            if (c != null) {
                combo.setBackground(c.getBackground());
            return combo;
        public void itemStateChanged(java.awt.event.ItemEvent e) {
            Base base = new Base();
            Statement sta = base.conectar();
            try {
                String asist;
                if (tabla.getValueAt(i,3).equals(new Boolean(true))) {
                    asist = "s";
                } else {
                    asist = "n";
                ResultSet rs = sta.executeQuery("SELECT COUNT(ID_Cita) FROM Cita JOIN Pacientes ON Cita.RFC_Paciente " +
                        "= Pacientes.RFC_Paciente WHERE Nombre_Completo = '" + combo.getSelectedItem() + "'");
                rs.next();
                int result = rs.getInt("COUNT(ID_Cita)");
                rs = sta.executeQuery("SELECT Consultas FROM Ciclo JOIN Pacientes ON Ciclo.RFC_Paciente = Pacientes." +
                        "RFC_Paciente WHERE Nombre_Completo = '"+ combo.getSelectedItem() +"' AND Ciclo.Numero_Ciclo = " +
                        "Pacientes.Ciclo");
                rs.next();
                int maximo = rs.getInt("Consultas");
                /* if maximo is bigger than result plus 1, then it shows the alert, but it is shown even if I don't change the combo value!!!, this part only works if the default value of the combo is blank */
                if (maximo >= result +1 ) {
                    sta.executeUpdate("UPDATE Cita,Pacientes SET Cita.RFC_Paciente = Pacientes.RFC_Paciente WHERE " +
                            "Nombre_Completo = '" + combo.getSelectedItem() + "' AND ID_Cita = " + tabla.getValueAt(i,0));
                }else
                    javax.swing.JOptionPane.showMessageDialog(null,"No se puede agregar otra cita...");
            }catch (ArrayIndexOutOfBoundsException ex) {
                System.out.println (ex.getMessage());
            } catch (SQLException ex) {
                System.out.println (ex.getMessage());
            } finally {
                base.cerrar(sta);
    }So, I'd like to know why the alert appears twice when it works and why it appears even if the combo value ain't changed. I really hope anyone can help me. Thank you!

    if the first is bigger than the second it shows an alertIf you want to know when data is changed in the table then you use a TableModelListener, not an ItemListener. Here is a simple example:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=566133
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • JCombobox/Jtable

    Hi ,
    first of all, sry for my poor english.
    i have some questions maybe i can found help here:
    1-how could i populate a JCombobox respectively Jtable with data from a database?
    2-how do i retrieve data from a database with the input of my JCombobox respectively jtable by using the autogenerated primary key of the stored entities?
    thx for all the answers.
    nougs.

    It is possible to do the same-i mean to custom an Object- with all the swings Components such a Jtable ...?Thats what Swing is all about, using Models. The data in a Model is always an Object, which means it can be anything. That is why the more complex components, like JTable, JList, JTree all use renderers. You can store anything in the model and render it any way you want. The component then implements a default renderer to render String objects since that is common.
    Read the API for any JTable, JList and you will find a link to the Swing tutorial which will explain better how renderers work.

  • Different JComboBox in different Cells in a JTable

    Hi:
    I would like to make a JTable whose content would be several JBox with different values each one. That is to say, a double-column table with the value name in the first column and a range of possible values in the second column,
    Despite my efforts I was not able to do that. Every example that I found in the Web does not let different JComboBox per cell. They run with the same cell and values for each column.
    Can anybody help me?
    Thanks in advance.
    Carlos

    Here is an example that is based on camickr´s example:
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.*;
    import java.util.*;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.table.*;
    import javax.swing.JTable;
    import java.util.ArrayList;
    import javax.swing.DefaultCellEditor;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    public class TableCell extends JFrame
         JComboBox comboBox1 = new JComboBox();
         JComboBox comboBox2 = new JComboBox();
         JTable table;
         ArrayList<DefaultCellEditor> editors = new ArrayList<DefaultCellEditor>();
         TableCell()
              comboBox1.addItem("Tennis");
              comboBox1.addItem("Fotboll");
              comboBox1.addItem("Baseball");
              comboBox1.addItem("Handboll");
              comboBox2.addItem("USA");
              comboBox2.addItem("Brazil");
              comboBox2.addItem("Australia");
              comboBox2.addItem("China");
              comboBox2.addItem("Egypt");
              DefaultCellEditor dce1 = new DefaultCellEditor(comboBox1);
              DefaultCellEditor dce2 = new DefaultCellEditor(comboBox2);
              editors.add(dce1);
              editors.add(dce2);
              final JTable table = new JTable()
              { // anonym innerklass
                   private Class editingClass;
                   public TableCellRenderer getCellRenderer(int row, int column)
                        editingClass = null;
                        int modelColumn = convertColumnIndexToModel(column);
                        int modelRow = convertRowIndexToModel(row);
                        if (modelColumn == 1)
                             Class rowClass = getModel().getValueAt(row, modelColumn).getClass();
                             return getDefaultRenderer( rowClass );
                        else
                             return super.getCellRenderer(row, column);
                   public TableCellEditor getCellEditor(int row, int column)
                        editingClass = null;
                        int modelColumn = convertColumnIndexToModel(column);
                        int modelRow = convertRowIndexToModel(row);
                        if (modelColumn == 1)
                             if (modelRow == 5)     // cell number 5 in column 1 which is going to show the combobox
                                  return (DefaultCellEditor) editors.get(0);
                             if (modelRow == 6)     // cell number 6 in column 1 which is going to show the combobox
                                  return (DefaultCellEditor) editors.get(1);
                             else
                                  editingClass = getModel().getValueAt(modelRow, modelColumn).getClass();
                                  return getDefaultEditor( editingClass );
                        else
                             return super.getCellEditor(row, column);
              table.setModel(new javax.swing.table.DefaultTableModel
                   new Object [][]
                          {"String", "I'm a string"},
                        {"Date", new Date()},
                        {"Integer", new Integer(123)},
                        {"Double", new Double(123.45)},
                        {"Boolean", Boolean.TRUE},
                        {"Combobox 1", "COMBOBOX 1"},
                        {"Combobox 2", "COMBOBOX 2"}
                   new String [] { "Attribute", "Data" }
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableCell frame = new TableCell();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • Help required on JComboBox

    Hi I have 500 customers in the database. I have to display the customer names in a JComboBox so that user will select the customer name. here i have a problem. pulling 500 customers at a time and displaying them in combobox will take time. the customers may even grow up to thousands. so i don't want to display all the customer names at once in the JComboBox. First i want to display 50 names and when customer pulls the scrollbar to the end of the JComboBox popup then i want to add another 50. How can i do this?
    kindly help me in this regard. Thanks in advance.

    I do not think users would normally prefer to scroll through thousands or more items in a combo box to pick their choice. You may want to redesign your GUI somewhat like splitting the data into categories and use two combos, one for categories and one for the data and populate the data one based on the value selected on the category one. In case splitting like this is not possible then you may consider to apply some filtering in your JComboBox/JTable so that users can select their choice as they type. I guess this may be of some help to you
    http://www.glazedlists.com/Home
    http://www.glazedlists.com/documentation/tutorial-100

  • Get parent JFrame for displaying exception msg

    I have a problem.
    Lots of my application components are classes that extends JPanel
    In these classes lot's of different exception could be raised.
    Some of them I want[b] to show to user (invalid input, no DB connection error e.t.c.)
    I make may GUI with help of GUI-builder + I write own classes As I said. Then I initialize them on my form in code.
    How can I reach parent form and send message to user?
    Is there any common method like:
    getParentForm.showMessageDialog(String mesage);
    Did I explain my problem clearly...?

    No, FAQ - is pretty useless thing.
    I suggest this one idea:
    see visualization:
    http://foto.mail.ru/mail/ice_holod/114/s-494.jpg
    no read my idea. I hope you will undestand me.
    Excuse me for offtopic.
    I suggest to develop "wisdom master.
    This master will give user solution for his problem.
    It will look like interactive dialog.
    For example, I have a question: �I want to put JComboBox into JTable�.
    I open �wisdom master�
    There I see list of topics:
    1.SWING/AWT
    Database
    Java language basics
    I choose �SWING�.
    2.The I see lest of SWING components, which were discussed million times:
    JFrame
    JTable
    JComboBox
    e.t.c.
    I choose �JTable�.
    3.Then I see list of ready solutions divided into categories:
    Embed something (embed checkboxes, comboboxes e.t.c.)
    Control data in JTable (add/delete row)
    e.t.c.
    I choose �Embed something�
    4.Then I see description and links to several threads:
    Embed combobox (several links to most valuable threads)
    Embed checkbox (several links to most valuable threads)
    e.t.c.
    BUT!
    If I would choose JComboBox instead of JTable on step #2 anyway I will get JComboBox + JTable solutions through master.
    See this chain: SWING->JComboBox (I did not choose JTable)->Embed somewhere->Embed into JTable
    Of course, such �wisdom master� will not help starters. Sometimes they even can�t understand what they need and what to search (I am a starter and sometimes I do not know what exactly to read, and where to search�)
    But, I think such service will help users which familiar with Java technology. The y will not have to read �search results� and million topics.
    The way to solution will be shorter.
    The MAIN PROBLEMS are
    1.     Separate food solutions and useful threads
    2.     Develop categories. We do not have to create many categories, user can lost in these categories, we can�t reduce their quantity. We have to find gold middle.
    3.     Develop good graph (graph branches = search chains). Categories=nodes of Graph

  • Detecting changes

    hi folks,
    I have a swing application that has a functionality to save the input. I want to know what is the common way to detect modification of input. If there's modification, i want to prompt the user to save if he/she is closing down the app. I'm thinking about using a listener on all input components(JTextField, JList, JComboBox,JTable,JButton). But the listener would be different for each type of component, ActionListener for JButton, CaretListener for JTextField, ListSelectionListener for JList, ect. So I want to write a class that implements all these Listeners, and if any of those events is triggered, then I know there's modification been made.
    My question is: is there a better/more efficient/more elegant way of detecting changes in my app?
    If not, any comments on my approach?
    thanks!!

    You can write an unique class implementing DocumentListener, ActionListener, ItemListener, etc..
    But you still have to add the listener to all the components.
    I'm thinking you can write a method void register(JComponent pane) Depending on the class JTextField,JCheckBox, etc... you add the class as a DocumentListener,
    as an ActionListener, etc. If the component is a container, you can recursively invoke the method
    for all the children

  • The correct approach to intercept TAB key

    Dear Experts,
    I have developed a GUI out of javax.swing. The GUI consists of JFrame, several JPanels and javax components, such as JTextField, JLabel, JComboBox, JTable and many more.
    Now, I want to change the behavior when user presses TAB key. By default TAB key moves focus from a component to another component. How can I disable this?
    I come to two alternatives that I am not sure which one is the correct approach. Could you please advise me?
    Alternative 1.
    Use key binding on GlassPane.
    Alternative 2.
    Use event-handling on GlassPane.
    If those alternatives are not the best one, could you please provide another alternative?
    I have tried the following, but they didn't work...
    Action doNothing = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("Tab-key is pressed.");
    cmbPCode.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "doNothing");
    cmbPCode.getActionMap().put("doNothing", doNothing);or
    getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "doNothing");
    getRootPane().getActionMap().put("doNothing", doNothing);where cmbPCode is a JComboBox that receives focus when the GUI shows up.
    Thanks for your help,
    Patrick
    Edited by: Patrick_Stiady on Mar 31, 2009 6:51 AM

    Thank you for the advice. I am developing an application where the user is not computer literated, so that I have to limit functional key as many as possible and only allow several keys to be active. For example, I don't want TAB key to change the focus, instead I want TAB key to do nothing.
    I have tried keybinding, because I think this is the most relevant, but somehow I failed to recognize which component should be bound with keybinding. I have tried to change the input map of the component that receives the focus when the GUI is displayed (cmbPCode) as can be seen on my first post. I also tried to change the input map of the root pane. Both are not successful.
    Now, I wonder whether
    1. it does not work because the key is not consume()?
    2. Or should I use key listener, which I would only use if keybinding were unable to serve my goal?
    3. Or should I learn how to intercept key on the glass pane?
    4. Is keybinding able to nullify default action, such as changing focus by TAB key? I am asking this, because I'm going to nullify other important key such as ENTER key.
    Thank you for any guidance,
    Patrick

  • GridBagLayout - need to keep components stable

    Is there a way, using GridBagLayout, to keep the components (JTable, JComboBox) from resizing and/or repositioning themselves when the window resizes? I have the following positioned vertically (JLabel-JComboBox-JTable-JLabel):
    GridBagConstraints lgbc = new GridBagConstraints ();
    this.setLayout ( new GridBagLayout() );
    // Title label
    lgbc = new GridBagConstraints();
    lgbc.gridx = 0;
    lgbc.gridy = 0;
    lgbc.weightx = 0.0;
    lgbc.weighty = 0.0;
    lgbc.insets = new Insets ( 4,4,4,4 );
    lgbc.fill = GridBagConstraints.HORIZONTAL;
    lgbc.anchor = GridBagConstraints.NORTHWEST;
    this.add ( jlbTitle, lgbc );
    // Combo box
    lgbc = new GridBagConstraints();
    lgbc.gridy = 1;
    lgbc.weightx = 0.0;
    lgbc.weighty = 0.0;
    lgbc.fill = GridBagConstraints.HORIZONTAL;
    lgbc.insets = new Insets ( 2, 2, 2, 2 );
    lgbc.anchor = GridBagConstraints.NORTHWEST;
    this.add ( jcb, lgbc );
    // Scroll pane
    lgbc = new GridBagConstraints();
    lgbc.gridy = 2;
    lgbc.weightx = 1.0;
    lgbc.weighty = 1.0;
    lgbc.fill = GridBagConstraints.NONE;
    lgbc.anchor = GridBagConstraints.NORTHWEST;
    jsp.setMinimumSize ( jsp.getPreferredSize() );
    this.add ( jsp, lgbc );
    // Message label
    lgbc = new GridBagConstraints();
    lgbc.gridy = 3;
    lgbc.weightx = 0.0;
    lgbc.weighty = 0.0;
    lgbc.fill = GridBagConstraints.HORIZONTAL;
    lgbc.anchor = GridBagConstraints.NORTHWEST;
    this.add ( jlbMsg, lgbc );     
    What's happening is that when the window resizes to a smaller size, the panel containing the above components gets larger, and the components expand (via the fill) to take over the excess horizontal space, which I don't want to happen. However, if I remove the fill, the combobox in particular is not large enough to show its data.
    For this particular panel, everything else is working as desired (i.e. when the window resizes, the components don't move to the center or anything like that). I have at least 2 more panels to add to this window, but wanted to get this one working correctly before adding the other panels.
    Any suggestions on how to make sure the components are the same size when the window resizes?
    Thanks,
    Van Williams

    Thomas,
    thanks for the suggestion. However, the same thing is happening when I add the following code to the original code:
    lgbc = new GridBagConstraints();
    lgbc.gridy = 4;
    lgbc.weightx = 0.0;
    lgbc.weighty = 1.0;
    this.add ( new JPanel(), lgbc );
    I put a border around the object (the JLabels, JComboBox, and JTable combined) to see what's happening. When the window the object is placed on is shrunk vertically to be smaller than the JTable, the panel containing the object expands in size. Consequently, so do the JTable and JComboBox. I'd like for the components within the panel (and all other components I have yet to place on the window) to remain the same size and in the same position during all window resizing. Note... horizontal resizing doesn't seem to affect the component's size/position at all, which is exactly what I want.
    I've tried any number of things, including setting preferred/minimum/maximum sizes, and various combinations of weightx/weighty/fill/anchor, all without success. The way the code stands now is the best bet so far, but by no means the way I would like it to be.
    Thanks for any suggestions anyone may have.
    Thanks,
    Van Williams

  • Strategy to detect changes on screen

    I have a JPane which is in a JFrame and pane holds all my gui components like JComboBox , JTable , JStringField etc....what is the
    best , easiest way to implement a "listener" which will sense if a user has changed any component value so that I can give a message "Please save changes or u will lose it" if user "Xes" out of the screen...
    Thanks for your time

    1) Have a 'boolean = false' to record the change
    2) add appropriate listeners to all your components... JTable.addTableModelListener / JTextField.addKeyListener / JComboBox.addActionListener etc etc
    3) any event on the above listeners... will set the 'boolean = true', with a bit faster performance... use this < if(boolean = false) boolean = true; >
    4) when user "Xes" out of the screen... check the boolean value, if it's true, then ask the user if changes need to be saved.

  • How do you set new items within a JComboBox that is within a JTable

    I have searched and searched for the answer to this and do not thing there is one. I have a JTable that has 5 columns. 2 of the columns use DefaultCellRenderers where a JComboBox is used. One of the columns has a value of different football positions. The other has a value of the different players. When a user enters a particular position such as Kickers I want all the Kickers to be showin within the Players JComboBox within the table.
    The problem is that I ONLY want the cell to be modified within that row and column that the position was changed. I have found ways to modify the component but it modifies it for the whole Column. I only want it to be modified for the player cell within the row that the Position was modified. Bottom line is that I just want to modify the JComboBox's components.
    If anyone has had this challenge before please advise.

    I'm not sure I fully understood what you wanted. Does the following little program help you?import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumnModel;
    import java.awt.*;
    * User: weebib
    * Date: 29 janv. 2005
    * Time: 23:37:57
    public class FootballTable extends JPanel {
         private static final String[] COLUMN_NAMES = {"Position", "Name"};
         private static final String[] POSITIONS = {"goal", "arriere", "milieu", "avant"};
         private static final String[] GOALS = {"goal1", "goal2", "goal3"};
         private static final String[] ARRIERES = {"arriere1", "arriere2", "arriere3"};
         private static final String[] MILIEUX = {"milieu1", "milieu2", "milieu3"};
         private static final String[] AVANTS = {"avant1", "avant2", "avant3"};
         public FootballTable() {
              super(new BorderLayout());
              DefaultTableModel model = new DefaultTableModel(COLUMN_NAMES, 10);
              final JTable table = new JTable(model);
              TableColumnModel columnModel = table.getColumnModel();
              columnModel.getColumn(0).setCellEditor(new DefaultCellEditor(new JComboBox(POSITIONS)));
              columnModel.getColumn(1).setCellEditor(new DefaultCellEditor(new JComboBox()) {
                   public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
                        JComboBox nameComboBox = (JComboBox)super.getTableCellEditorComponent(table, value, isSelected, row, column);
                        Object position = table.getValueAt(row, 0);
                        if (position == null) {
                             nameComboBox.setModel(new DefaultComboBoxModel());
                        } else if (position.equals("goal")) {
                             nameComboBox.setModel(new DefaultComboBoxModel(GOALS));
                        } else if (position.equals("arriere")) {
                             nameComboBox.setModel(new DefaultComboBoxModel(ARRIERES));
                        } else if (position.equals("milieu")) {
                             nameComboBox.setModel(new DefaultComboBoxModel(MILIEUX));
                        } else if (position.equals("avant")) {
                             nameComboBox.setModel(new DefaultComboBoxModel(AVANTS));
                        } else {
                             nameComboBox.setModel(new DefaultComboBoxModel());
                        return nameComboBox;
              add(new JScrollPane(table), BorderLayout.CENTER);
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
              } catch (Exception e) {
                   e.printStackTrace();
              final JFrame frame = new JFrame(FootballTable.class.getName());
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(new FootballTable());
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.setSize(400, 300);
                        frame.show();
    }Sorry for the French words, I have no idea how they are called in english (and too lazy to search).
    There is another solution. You also can override the table's prepareEditor method and add the relevant code before returning the Component.

  • Not Updating the Values in the JComboBox and JTable

    Hi Friends
    In my program i hava Two JComboBox and One JTable. I Update the ComboBox with different field on A Table. and then Display a list of record in the JTable.
    It is Displaying the Values in the Begining But when i try to Select the Next Item in the ComboBox it is not Updating the Records Eeither to JComboBox or JTable.
    MY CODE is this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.DefaultComboBoxModel.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    public class SearchBook extends JDialog implements ActionListener
         private JComboBox comboCategory,comboAuthor;
         private JSplitPane splitpane;
         private JTable table;
         private JToolBar toolBar;
         private JButton btnclose, btncancel;
         private JPanel panel1,panel2,panel3,panel4;
         private JLabel lblCategory,lblAuthor;
         private Container c;
         //DefaultTableModel model;
         Statement st;
         ResultSet rs;
         Vector v = new Vector();
         public SearchBook (Connection con)
              // Property for JDialog
              setTitle("Search Books");
              setLocation(40,110);
              setModal(true);
              setSize(750,450);
              // Creating ToolBar Button
              btnclose = new JButton(new ImageIcon("Images/export.gif"));
              btnclose.addActionListener(this);
              // Creating Tool Bar
              toolBar = new JToolBar();
              toolBar.add(btnclose);
              try
                   st=con.createStatement();
                   rs =st.executeQuery("SELECT BCat from Books Group By Books.BCat");
                   while(rs.next())
                        v.add(rs.getString(1));
              catch(SQLException ex)
                   System.out.println("Error");
              panel1= new JPanel();
              panel1.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
              lblCategory = new JLabel("Category:");
              lblCategory.setHorizontalAlignment (JTextField.CENTER);
              c.gridx=2;
              c.gridy=2;
              panel1.add(lblCategory,c);
              comboCategory = new JComboBox(v);
              comboCategory.addActionListener(this);
              c.ipadx=20;
              c.gridx=3;
              c.gridwidth=1;
              c.gridy=2;
              panel1.add(comboCategory,c);
              lblAuthor = new JLabel("Author/Publisher:");
              c.gridwidth=2;
              c.gridx=1;
              c.gridy=4;
              panel1.add(lblAuthor,c);
              lblAuthor.setHorizontalAlignment (JTextField.LEFT);
              comboAuthor = new JComboBox();
              comboAuthor.addActionListener(this);
              c.insets= new Insets(20,0,0,0);
              c.ipadx=20;
              c.gridx=3;
              c.gridy=4;
              panel1.add(comboAuthor,c);
              comboAuthor.setBounds (125, 165, 175, 25);
              table = new JTable();
              JScrollPane scrollpane = new JScrollPane(table);
              //panel2 = new JPanel();
              //panel2.add(scrollpane);
              splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,panel1,scrollpane);
              splitpane.setDividerSize(15);
              splitpane.setDividerLocation(190);
              getContentPane().add(toolBar,BorderLayout.NORTH);
              getContentPane().add(splitpane);
         public void actionPerformed(ActionEvent ae)
              Object obj= ae.getSource();
              if(obj==comboCategory)
                   String selecteditem = (String)comboCategory.getSelectedItem();
                   displayAuthor(selecteditem);
                   System.out.println("Selected Item"+selecteditem);
              else if(obj==btnclose)
                   setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
              else if(obj==comboAuthor)
                   String selecteditem1 = (String)comboAuthor.getSelectedItem();
                   displayavailablity(selecteditem1);
                   //System.out.println("Selected Item"+selecteditem1);
                   System.out.println("Selected Author"+selecteditem1);
         private void displayAuthor(String selecteditem)
              try
              {     Vector data = new Vector();
                   rs= st.executeQuery("SELECT BAuthorandPublisher FROM Books where BCat='" + selecteditem + "' Group By Books.BAuthorandPublisher");
                   System.out.println("Executing");
                   while(rs.next())
                        data.add(rs.getString(1));
                   //((DefaultComboBoxModel)comboAuthor.getModel()).setVectorData(data);
                   comboAuthor.setModel(new DefaultComboBoxModel(data));
              catch(SQLException ex)
                   System.out.println("ERROR");
         private void displayavailablity(String selecteditem1)
                   try
                        Vector columnNames = new Vector();
                        Vector data1 = new Vector();
                        rs= st.executeQuery("SELECT * FROM Books where BAuthorandPublisher='" + selecteditem1 +"'");     
                        ResultSetMetaData md= rs.getMetaData();
                        int columns =md.getColumnCount();
                        String booktblheading[]={"Book ID","Book NAME","BOOK AUTHOR/PUBLISHER","REFRENCE","CATEGORY"};
                        for(int i=1; i<= booktblheading.length;i++)
                             columnNames.addElement(booktblheading[i-1]);
                        while(rs.next())
                             Vector row = new Vector(columns);
                             for(int i=1;i<=columns;i++)
                                  row.addElement(rs.getObject(i));
                             data1.addElement(row);
                             //System.out.println("data is:"+data);
                        ((DefaultTableModel)table.getModel()).setDataVector(data1,columnNames);
                        //DefaultTableModel model = new DefaultTableModel(data1,columnNames);
                        //table.setModel(model);
                        rs.close();
                        st.close();
                   catch(SQLException ex)
    }Please check my code and give me some Better Solution
    Thank you

    You already have a posting on this topic:
    http://forum.java.sun.com/thread.jspa?threadID=5143235

  • JTable with JComboBox

    Hi friends,
    I am adding JComboBox in JTable its working properly
    But data is not adding dynamically to JComboBox
    I am Sending my Code plz give me reply
    I am Struggleing from 1 week on wards
    package com.dnt.autopopulation;
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableColumn;
    import java.awt.event.*;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.event.TableModelEvent;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Locale;
    import java.text.SimpleDateFormat;
    import java.util.Vector;
    import javax.swing.border.*;
    import com.dnt.eaip.Connectmagr;
    import com.dnt.eaip.*;
    import com.dnt.util.*;
    import javax.swing.plaf.ButtonUI;
    import com.dnt.admin.EndStartDateCheck;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumnModel;
    public class AutoPopRollBack extends JPanel {
    boolean selection = false;
    public static final int HAND_CURSOR = 12;
    Cursor cursor = new Cursor(HAND_CURSOR);
    int selectedRow = -1;
    ImageIcon headertop1 = new ImageIcon("./images/k2topbar.gif");
    JLabel HeaderLabe = new JLabel(headertop1);
    Border border1 = new EtchedBorder(EtchedBorder.RAISED, Color.white, Color.blue);
    Border border2 = BorderFactory.createBevelBorder(BevelBorder.RAISED,
    new Color(154, 254, 211), new Color(108, 178, 148),
    new Color(37, 60, 50), new Color(53, 87, 72));
    DefaultTableModel dm = new DefaultTableModel();
    Vector searchlist = new Vector();
    Vector rows = new Vector();
    Vector returnList;
    Connectmagr objConnectmagr = new Connectmagr();
    JFrame frame = new JFrame();
    JLabel headlab = new JLabel();
    JCalendarComboBox EndDateTxt;
    JLabel HawbLab = new JLabel();
    JTextField HawbTxt = new JTextField();
    JLabel AgentLab = new JLabel();
    JLabel StartDateLab = new JLabel();
    JCalendarComboBox StartDateTxt;
    JComboBox AgentLBox = new JComboBox();
    JLabel EnddateLab = new JLabel();
    JPanel ReviewJobsPane = new JPanel();
    JButton SearchBtn = new JButton();
    ButtonUI ui = new com.sun.java.swing.plaf.motif.MotifButtonUI();
    ArrayList AgentList = new ArrayList();
    JComboBox DocTypeLBox = new JComboBox();
    JLabel doctypelab = new JLabel();
    JPanel displayPanel = new JPanel();
    ButtonGroup group1;
    JRadioButton rb;
    JTable table;
    public ArrayList jobList = new ArrayList();
    public AutoPopRollBack(JFrame frame, ArrayList agentArrayList) {
    this.frame = frame;
    this.AgentList = agentArrayList;
    try {
    jbInit();
    } catch (Exception e) {
    e.printStackTrace();
    public void jbInit() throws Exception {
    Calendar cal = Calendar.getInstance();
    Locale loc = new Locale("");
    SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");
    EndDateTxt = new JCalendarComboBox(cal, loc, dateformat);
    StartDateTxt = new JCalendarComboBox(cal, loc, dateformat);
    HeaderLabe.setBackground(new Color(250, 233, 216));
    HeaderLabe.setBounds(new Rectangle(0, 0, 830, 33));
    this.setLayout(null);
    this.setBackground(SystemColor.control);
    headlab.setBackground(new Color(250, 233, 216));
    headlab.setFont(new java.awt.Font("Verdana", 1, 12));
    headlab.setForeground(Color.blue);
    headlab.setHorizontalAlignment(SwingConstants.CENTER);
    headlab.setText(" :: Auto Population Rollback");
    headlab.setBounds(new Rectangle(39, 2, 247, 25));
    EndDateTxt.setBounds(new Rectangle(474, 36, 116, 18));
    EndDateTxt.setBackground(Color.white);
    EndDateTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
    EndDateTxt.setForeground(Color.blue);
    EndDateTxt.setBorder(null);
    HawbLab.setFont(new java.awt.Font("Dialog", 0, 13));
    HawbLab.setForeground(Color.blue);
    HawbLab.setHorizontalAlignment(SwingConstants.RIGHT);
    HawbLab.setText("Job No/Airway Bill No:");
    HawbLab.setBounds(new Rectangle(326, 14, 146, 18));
    HawbTxt.setBounds(new Rectangle(474, 14, 125, 18));
    HawbTxt.setText("");
    HawbTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
    HawbTxt.setForeground(Color.blue);
    HawbTxt.setBorder(border1);
    AgentLab.setFont(new java.awt.Font("Dialog", 0, 13));
    AgentLab.setForeground(Color.blue);
    AgentLab.setHorizontalAlignment(SwingConstants.RIGHT);
    AgentLab.setText("<html>Agent:<font size=\'4\' color=\"#993333\">*</font></html>");
    AgentLab.setBounds(new Rectangle(31, 14, 97, 18));
    StartDateLab.setFont(new java.awt.Font("Dialog", 0, 13));
    StartDateLab.setForeground(Color.blue);
    StartDateLab.setHorizontalAlignment(SwingConstants.RIGHT);
    StartDateLab.setText("Start Date:");
    StartDateLab.setBounds(new Rectangle(23, 36, 105, 18));
    StartDateTxt.setBounds(new Rectangle(129, 36, 116, 18));
    StartDateTxt.setBackground(Color.white);
    StartDateTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
    StartDateTxt.setForeground(Color.blue);
    StartDateTxt.setBorder(null);
    AgentLBox.setBackground(Color.white);
    AgentLBox.setFont(new java.awt.Font("Verdana", 0, 13));
    AgentLBox.setForeground(Color.blue);
    AgentLBox.setBounds(new Rectangle(129, 14, 178, 18));
    AgentLBox.setFont(new java.awt.Font("Times New Roman", 1, 10));
    EnddateLab.setFont(new java.awt.Font("Dialog", 0, 13));
    EnddateLab.setForeground(Color.blue);
    EnddateLab.setHorizontalAlignment(SwingConstants.RIGHT);
    EnddateLab.setText("End Date:");
    EnddateLab.setBounds(new Rectangle(391, 36, 81, 18));
    ReviewJobsPane.setBackground(new Color(240, 233, 216));
    ReviewJobsPane.setBorder(BorderFactory.createLineBorder(Color.black));
    ReviewJobsPane.setBounds(new Rectangle(69, 47, 705, 96));
    ReviewJobsPane.setLayout(null);
    SearchBtn.setUI(ui);
    SearchBtn.setCursor(cursor);
    SearchBtn.setBackground(new Color(76, 125, 104));
    SearchBtn.setBounds(new Rectangle(377, 153, 89, 19));
    SearchBtn.setFont(new java.awt.Font("Tahoma", 1, 10));
    SearchBtn.setForeground(Color.white);
    SearchBtn.setBorder(border2);
    SearchBtn.setOpaque(true);
    SearchBtn.setFocusPainted(false);
    SearchBtn.setText("Search");
    SearchBtn.addActionListener(new AutoPopRollBack_SearchBtn_actionAdapter(this));
    for (int i = 0; i < AgentList.size(); i++)
    AgentLBox.addItem( (String) AgentList.get(i));
    DocTypeLBox.setFont(new java.awt.Font("Verdana", 0, 13));
    DocTypeLBox.setForeground(Color.blue);
    DocTypeLBox.setMinimumSize(new Dimension(22, 19));
    DocTypeLBox.setBounds(new Rectangle(129, 58, 179, 18));
    DocTypeLBox.setFont(new java.awt.Font("Times New Roman", 1, 10));
    DocTypeLBox.addItem("New Jobs");
    DocTypeLBox.addItem("Draft jobs");
    DocTypeLBox.addItem("Finished jobs");
    doctypelab.setBounds(new Rectangle(7, 58, 121, 18));
    doctypelab.setText("<html>Document Type:<font size=\'4\' color=\"#993333\">*</font></html>");
    doctypelab.setHorizontalAlignment(SwingConstants.RIGHT);
    doctypelab.setForeground(Color.blue);
    doctypelab.setFont(new java.awt.Font("Dialog", 0, 13));
    displayPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    displayPanel.setBounds(new Rectangle(69, 182, 705, 315));
    this.add(headlab, null);
    this.add(HeaderLabe, null);
    this.add(ReviewJobsPane, null);
    ReviewJobsPane.add(HawbLab, null);
    ReviewJobsPane.add(AgentLab, null);
    ReviewJobsPane.add(AgentLBox, null);
    ReviewJobsPane.add(StartDateLab, null);
    ReviewJobsPane.add(StartDateTxt, null);
    ReviewJobsPane.add(HawbTxt, null);
    ReviewJobsPane.add(EnddateLab, null);
    ReviewJobsPane.add(EndDateTxt, null);
    ReviewJobsPane.add(DocTypeLBox, null);
    ReviewJobsPane.add(doctypelab, null);
    this.add(SearchBtn, null);
    this.add(displayPanel, null);
    //this.add(scrollPaneView, null);
    // scrollPaneView.getViewport().add(displayPanel, null);
    this.setVisible(true);
    void FieldEditable(boolean str) {
    StartDateTxt.setEnabled(str);
    EndDateTxt.setEnabled(str);
    public static void main(String args[]) {
    JFrame frame = new JFrame();
    ArrayList agentlist = new ArrayList();
    agentlist.add(0, "BF0651");
    agentlist.add(1, "PF0010");
    AutoPopRollBack objAutoPopRollBack = new AutoPopRollBack(frame, agentlist);
    frame.getContentPane().add(objAutoPopRollBack);
    frame.setBounds(new Rectangle(0, 0, 820, 593));
    frame.setVisible(true);
    void SearchBtn_actionPerformed(ActionEvent e) {
    displayPanel.setVisible(false);
    Vector data=new Vector();
    rows.removeAllElements();
    boolean flag = true;
    String che = new EndStartDateCheck().crossCheck(StartDateTxt.getCalendar(), EndDateTxt.getCalendar());
    try {
    if(HawbTxt.getText().equalsIgnoreCase("")){
    if (StartDateTxt._spinner.getText().equalsIgnoreCase("")) {
    JOptionPane.showMessageDialog(this, "Please Select Start Date",
    "Warning", JOptionPane.WARNING_MESSAGE);
    flag = false;
    else if (!che.equalsIgnoreCase("")) {
    JOptionPane.showMessageDialog(frame, che, "Message Window", JOptionPane.INFORMATION_MESSAGE);
    flag = false;
    }else{
    FieldEditable(true);
    if (flag) {
    try {
    displayPanel.removeAll();
    } catch (Exception ex) {
    rows.removeAllElements();
    data.removeAllElements();
    SearchBtn.setEnabled(true);
    searchlist.add(0, AgentLBox.getSelectedItem().toString().trim());
    if (!HawbTxt.getText().trim().equalsIgnoreCase(""))
    searchlist.add(1, HawbTxt.getText().toString().trim());
    else
    searchlist.add(1, "");
    searchlist.add(2, new Integer(DocTypeLBox.getSelectedIndex() + 1));
    String startDate = new ConvertDate().convertddMM_To_MMdd(StartDateTxt._spinner.getText());
    String endDate = new ConvertDate().convertddMM_To_MMdd(EndDateTxt._spinner.getText());
    Vector columns = new Vector();
    columns.add(0, "");
    columns.add(1, "JOB No");
    columns.add(2, "Status");
    columns.add(3, "Current Form Type");
    columns.add(4, "New Form Type");
    System.out.println("Before calling Data Base");
    jobList = objConnectmagr.AutoRollBackSearch(searchlist, startDate, endDate, "AutoPopRollBack");
    if (jobList.size() > 0) {
    for (int i = 0; i < jobList.size(); i++) {
    ArrayList temp = new ArrayList();
    temp = (ArrayList) jobList.get(i);
    Vector col = new Vector();
    col.add(0, new Boolean(false));
    col.add(1, temp.get(0).toString().trim());
    col.add(2, temp.get(1).toString().trim());
    col.add(3, temp.get(2).toString().trim());
    Vector tempstr=new Vector();
    String [] tem=temp.get(3).toString().trim().split("\\|");
    tempstr.removeAllElements();
    for(int k=0;k<tem.length;k++)
    tempstr.add(k,tem[k]);
    col.add(4, new JComboBox(tempstr));
    data.add(col);
    dm.setDataVector(data, columns);
    table = new JTable(dm) {
    public void tableChanged(TableModelEvent e) {
    super.tableChanged(e);
    public boolean isCellEditable(int rowIndex, int vColIndex) {
    return true;
    JScrollPane scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    table.setColumnSelectionAllowed(false);
    table.setRowSelectionAllowed(false);
    table.setCellSelectionEnabled(false);
    table.setBackground(SystemColor.inactiveCaptionText);
    table.setRowHeight(20);
    JTableHeader head = table.getTableHeader();
    head.setSize(850, 75);
    table.setTableHeader(head);
    table.getTableHeader().setFont(new Font("Verdana", Font.BOLD, 11));
    table.getTableHeader().setBackground(new Color(130, 170, 150));
    table.getTableHeader().setForeground(Color.BLUE);
    table.getTableHeader().setReorderingAllowed(false);
    table.getTableHeader().setResizingAllowed(false);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    table.setFont(new java.awt.Font("MS Sans Serif", 0, 13));
    table.setForeground(new Color(125, 25, 0));
    TableColumn col = table.getColumnModel().getColumn(0);
    col.setMinWidth(75);
    col.setMaxWidth(75);
    TableColumn col1 = table.getColumnModel().getColumn(1);
    col1.setMinWidth(150);
    col1.setMaxWidth(150);
    TableColumn col2 = table.getColumnModel().getColumn(2);
    col2.setMinWidth(150);
    col2.setMaxWidth(150);
    TableColumn col3 = table.getColumnModel().getColumn(3);
    col3.setMinWidth(150);
    col3.setMaxWidth(150);
    TableColumn col4 = table.getColumnModel().getColumn(4);
    col4.setMinWidth(160);
    col4.setMaxWidth(160);
    TableColumn tc = table.getColumnModel().getColumn(0);
    tc.setCellEditor(table.getDefaultEditor(Boolean.class));
    tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
    tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener()));
    Vector tempstr=new Vector();
    for(int j=0;j<jobList.size();j++){
    ArrayList temlist=(ArrayList)jobList.get(j);
    String [] tem=temlist.get(3).toString().trim().split("\\|");
    tempstr.removeAllElements();
    for(int k=0;k<tem.length;k++)
    tempstr.add(k,tem[k]);
    JComboBox portTypesCombo = new JComboBox(tempstr);
    col4.setCellEditor(new DefaultCellEditor(portTypesCombo));
    col4 = table.getColumnModel().getColumn(4);
    col4.setCellEditor(new MyComboBoxEditor(tempstr));
    // If the cell should appear like a combobox in its
    // non-editing state, also set the combobox renderer
    col4.setCellRenderer(new MyComboBoxRenderer(tempstr));
    System.out.println(tempstr);
    displayPanel.setLayout(new BorderLayout());
    displayPanel.add(table.getTableHeader(), BorderLayout.PAGE_START);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    table.setEditingColumn(0);
    int column = 0;
    if (e.getClickCount() == 1) {
    Point p = e.getPoint();
    selectedRow = table.rowAtPoint(p);
    column = table.columnAtPoint(p);
    System.out.println(table.isCellEditable(selectedRow, column));
    if (column != 0) {
    selectedRow = -1;
    returnList = new Vector();
    returnList = (Vector) rows.get(selectedRow);
    else if (column == 0) {
    table.revalidate();
    table.repaint();
    scroll.getViewport().add(table);
    displayPanel.add(scroll, BorderLayout.CENTER);
    displayPanel.setVisible(true);
    else {
    JOptionPane.showMessageDialog(this, "No Data Available");
    } catch (Exception e1) {
    e1.printStackTrace();
    class MyItemListener implements ItemListener {
    public void itemStateChanged(ItemEvent e) {
    Object source = e.getSource();
    if (source instanceof AbstractButton == false)return;
    boolean checked = e.getStateChange() == ItemEvent.SELECTED;
    for (int x = 0, y = table.getRowCount(); x < y; x++) {
    table.setValueAt(new Boolean(checked), x, 0);
    class AutoPopRollBack_SearchBtn_actionAdapter implements java.awt.event.ActionListener {
    AutoPopRollBack adaptee;
    AutoPopRollBack_SearchBtn_actionAdapter(AutoPopRollBack adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.SearchBtn_actionPerformed(e);
    class RadioButtonRenderer implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (value == null)return null;
    return (Component) value;
    class RadioButtonEditor extends DefaultCellEditor implements ItemListener {
    private JRadioButton button;
    public RadioButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int row,
    int column) {
    if (value == null)return null;
    button = (JRadioButton) value;
    button.addItemListener(this);
    return (Component) value;
    public Object getCellEditorValue() {
    button.removeItemListener(this);
    return button;
    public void itemStateChanged(ItemEvent e) {
    super.fireEditingStopped();
    class CheckCellRenderer extends JCheckBox implements TableCellRenderer {
    protected static Border m_noFocusBorder;
    public CheckCellRenderer() {
    super();
    m_noFocusBorder = new EmptyBorder(1, 2, 1, 2);
    setOpaque(true);
    setBorder(m_noFocusBorder);
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
    int row, int column) {
    if (value instanceof Boolean) {
    Boolean b = (Boolean) value;
    setSelected(b.booleanValue());
    setBackground(isSelected && !hasFocus ?
    table.getSelectionBackground() : table.getBackground());
    setForeground(isSelected && !hasFocus ?
    table.getSelectionForeground() : table.getForeground());
    setFont(table.getFont());
    setBorder(hasFocus ? UIManager.getBorder(
    "Table.focusCellHighlightBorder") : m_noFocusBorder);
    return this;
    class CheckBoxHeader extends JCheckBox implements TableCellRenderer, MouseListener {
    protected CheckBoxHeader rendererComponent;
    protected int column;
    protected boolean mousePressed = false;
    public CheckBoxHeader(ItemListener itemListener) {
    rendererComponent = this;
    rendererComponent.addItemListener(itemListener);
    public Component getTableCellRendererComponent(
    JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (table != null) {
    JTableHeader header = table.getTableHeader();
    if (header != null) {
    rendererComponent.setForeground(header.getForeground());
    rendererComponent.setBackground(header.getBackground());
    rendererComponent.setFont(new java.awt.Font("Verdana", 1, 10));
    header.addMouseListener(rendererComponent);
    setColumn(column);
    rendererComponent.setText("Select All");
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    return rendererComponent;
    protected void setColumn(int column) {
    this.column = column;
    public int getColumn() {
    return column;
    protected void handleClickEvent(MouseEvent e) {
    if (mousePressed) {
    mousePressed = false;
    JTableHeader header = (JTableHeader) (e.getSource());
    JTable tableView = header.getTable();
    TableColumnModel columnModel = tableView.getColumnModel();
    int viewColumn = columnModel.getColumnIndexAtX(e.getX());
    int column = tableView.convertColumnIndexToModel(viewColumn);
    if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) {
    doClick();
    public void mouseClicked(MouseEvent e) {
    handleClickEvent(e);
    ( (JTableHeader) e.getSource()).repaint();
    public void mousePressed(MouseEvent e) {
    mousePressed = true;
    public void mouseReleased(MouseEvent e) {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
    public MyComboBoxRenderer(Vector 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());
    // Select the current value
    setSelectedItem(value);
    return this;
    class MyComboBoxEditor extends DefaultCellEditor {
    public MyComboBoxEditor(Vector items) {
    super(new JComboBox(items));
    and Bringing data from data base by using this method
    if (i == 0) sqlString = "SELECT * FROM FLIGHTSEARCH WHERE AGENT_CODE='" + agentCode + "' and ISSUEDATE BETWEEN '" + startDate + "' and '" + endDate + "'";
    else sqlString = "SELECT * FROM FLIGHTSEARCH WHERE AGENT_CODE='" + agentCode + "' and JOB_NO='" + JobNo + "%'";
    st = con.createStatement();
    System.out.println("---new jobs search-->" + sqlString);
    rs = st.executeQuery(sqlString);
    while (rs.next()) {
    retVector = new ArrayList();
    retVector.add(0, rs.getString("JOBNO"));
    retVector.add(1, "New Job");
    retVector.add(2, rs.getString("DOC_TYPE"));
    String temp="";
    if(retVector.get(2).toString().trim().equalsIgnoreCase("K1")){
    temp="K8I|K8T";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K2")){
    temp="K8E";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8I")){
    // temp="K1|K8T";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8T")){
    temp="K1|K8I";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8E")){
    temp="K2";
    retVector.add(3,temp);
    retVector.add(3, rs.getString("AGENT_CODE"));
    retVectorlist.add(retVector);
    i am sending data To ComboBox like this
    if(retVector.get(2).toString().trim().equalsIgnoreCase("K1")){
    K8I and K8T
    if K2 adding k8E and for other types as mentioned above
    But for ComboBoxes it is showing same Items not changing
    Please any body can help to me
    Thanks and Regards
    Ravichandra

    If you want further help post a Short, Self Contained, Compilable and Executable, Example Program ([url http://homepage1.nifty.com/algafield/sscce.html]SSCCE) that demonstrates the problem.
    And don't forget to use [url http://forum.java.sun.com/help.jspa?sec=formatting]code formatting when posting code.

  • How can you use the Keyboard for a JComboBox within a JTable without F2

    I am brand new to Java and I can't seem to figure this out. I have a JTable with 4 columns. The first column is a jCheckBox which is working fine. The other three are JComboBoxes. They work fine when you click them and select from the list, but our end users only want to navigate with the keyboard. They want to be able to tab to the column and just start typing the first letter of the item that they want to choose from the list and have that pop up the list and scroll to the first item in the list that starts with the letter the typed. Does anyone know how to do this? I have been playing with this for a week now and I can't seem to make it work. Please help. Below is the code for my table. Any help would be appreciated greatly. Thanks,
    Lisa
         private void LoadSTCGTable(){
         //Connect to database
            try {
                    connection = ConnecttoDB.connect();
                    // Tell me why I couldn't connect
                } catch (ClassNotFoundException ex) {
                    ex.printStackTrace();
                } catch (SQLException ex) {
                    ex.printStackTrace();
         try {
                // Get listing of Squad Types
                tblSTCG.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {new Boolean(false), null, null, null},
                new String [] {
                    "SELECT", "SQUAD TYPE", "SQUAD CLASS", "SQUAD GROUP"
              //Add Checkbox column
               tblSTCG.getColumnModel().getColumn(0).setCellEditor(tblSTCG.getDefaultEditor(Boolean.class));
               tblSTCG.getColumnModel().getColumn(0).setCellRenderer(tblSTCG.getDefaultRenderer(Boolean.class));      
               tblSTCG.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
               Whichquerytoread = 1;
               GetSql();
               sql = textfileinfo;
               stmt = connection.createStatement();
               rs = stmt.executeQuery(sql);
               md = rs.getMetaData();
               typelist = new ArrayList();
               // Loop Through Results
               typelist.add(new PairedDescriptionCodeDesc("",""));
               while (rs.next())
                  int i = 1;
                 typelist.add( new PairedDescriptionCodeDesc(rs.getString(2),rs.getString(1)));
              s1 = new TreeSet(typelist);
              typelist = new ArrayList(s1);
              AllTypeList = new PairedDescriptionCodeDesc[typelist.size()];
              for (int i = 0; i<typelist.size(); i++)
                 AllTypeList=(PairedDescriptionCodeDesc)typelist.get(i);
    rs.close();
    catch (SQLException ex) {
    ex.printStackTrace();
    Vector typedata = new Vector();
    for (int i=0;i<typelist.size();i++)
    typedata.addElement((PairedDescriptionCodeDesc)typelist.get(i));
    cmboType = new JComboBox();
    cmboType.setModel(new DefaultComboBoxModel(typedata));
    cmboType.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
    cmboType = new JComboBox(AllTypeList);
    cmboType.setBorder(BorderFactory.createEmptyBorder());
    squadcol = tblSTCG.getColumnModel().getColumn(1);
    DefaultCellEditor cmboTypeEditor = new DefaultCellEditor(cmboType);
    cmboTypeEditor.addCellEditorListener(new NewRowCellEditorListener(tblSTCG));
    squadcol.setCellEditor(cmboTypeEditor);
    try {
    // Get listing of Squad Class
    Whichquerytoread = 2;
    GetSql();
    sql = textfileinfo;
    stmt = connection.createStatement();
    rs = stmt.executeQuery(sql);
    md = rs.getMetaData();
    classlist = new ArrayList();
    // Loop Through Results
    classlist.add(new PairedDescriptionCodeDesc("",""));
    while (rs.next())
    classlist.add(new PairedDescriptionCodeDesc(rs.getString(2),rs.getString(1)));
    s1 = new TreeSet(classlist);
    classlist = new ArrayList(s1);
    AllClassList = new PairedDescriptionCodeDesc[classlist.size()];
    for (int i = 1; i<classlist.size(); i++)
    AllClassList[i]=(PairedDescriptionCodeDesc)classlist.get(i);
    rs.close();
    catch (SQLException ex) {
    ex.printStackTrace();
    Vector classdata = new Vector();
    for (int i=0;i<classlist.size();i++)
    classdata.addElement((PairedDescriptionCodeDesc)classlist.get(i));
    cmboClass = new JComboBox();
    cmboClass.setModel(new DefaultComboBoxModel(classdata));
    cmboClass = new JComboBox(AllClassList);
    classcol = tblSTCG.getColumnModel().getColumn(2);
    DefaultCellEditor cmboClassEditor = new DefaultCellEditor(cmboClass);
    classcol.setCellEditor(new DefaultCellEditor(cmboClass));
    cmboClassEditor.addCellEditorListener(new NewRowCellEditorListener(tblSTCG));
    try {
    // Get listing of Squad Group
    Whichquerytoread = 3;
    GetSql();
    sql = textfileinfo;
    stmt = connection.createStatement();
    rs = stmt.executeQuery(sql);
    md = rs.getMetaData();
    grouplist = new ArrayList();
    // Loop Through Results
    grouplist.add(new PairedDescriptionCodeDesc("",""));
    while (rs.next())
    int i = 0;
    grouplist.add( new PairedDescriptionCodeDesc(rs.getString(2), rs.getString(1)));
    s1 = new TreeSet(grouplist);
    grouplist = new ArrayList(s1);
    AllGroupList = new PairedDescriptionCodeDesc[grouplist.size()];
    for (int i = 0; i<grouplist.size(); i++)
    AllGroupList[i]=(PairedDescriptionCodeDesc)grouplist.get(i);
    rs.close();
    catch (SQLException ex) {
    ex.printStackTrace();
    Vector groupdata = new Vector();
    for (int i=0;i<grouplist.size();i++)
    groupdata.addElement((PairedDescriptionCodeDesc)grouplist.get(i));
    cmboGroup = new JComboBox();
    cmboGroup.setModel(new DefaultComboBoxModel(groupdata));
    cmboGroup = new JComboBox(AllGroupList);
    groupcol = tblSTCG.getColumnModel().getColumn(3);
    DefaultCellEditor cmboEditor = new DefaultCellEditor(cmboGroup);
    cmboEditor.addCellEditorListener(new NewRowCellEditorListener(tblSTCG));
    groupcol.setCellEditor(cmboEditor);
    tblSTCG.setShowHorizontalLines(false);
    tblSTCG.setShowVerticalLines(false);
    TableColumnModel columnModel = tblSTCG.getColumnModel();
    TableColumn column;
    tblSTCG.getColumnModel().getColumn(0).setPreferredWidth(5);
    tblSTCG.getColumnModel().getColumn(1).setPreferredWidth(100);
    tblSTCG.getColumnModel().getColumn(2).setPreferredWidth(100);
    tblSTCG.getColumnModel().getColumn(3).setPreferredWidth(100);
    scpSTCG.setViewportView(tblSTCG);
    private class NewRowCellEditorListener implements CellEditorListener
    JTable editingTable;
    public NewRowCellEditorListener(JTable table)
    editingTable = table;
    public void editingStopped(ChangeEvent e)
    if(editingTable.getRowCount() == editingTable.getSelectedRow() + 1)
    ((DefaultTableModel)editingTable.getModel()).addRow(new Object [] {null, null, null, null});
    public void editingCanceled(ChangeEvent e)

    Final Cut Pro menu > Audio / Video Settings... (Cmd Opt Q) will show you al the various presets currently loaded
    Sequence menu > Settings... (Cmd Zero) will show you the current sequence's settings
    Edit > Item Properties > Format... (Cmd 9) will show you the selected clip's properties

  • How can I surrend the focus of Jcombobox in Jtable?

    There are a jcombobox for each row of a jtable. I can click each cell to choose some value from the item list of jcombobox.
    The problem is, when I import data into the table by changing the values of tablemodel, if some cell still hold the focus, the table won't show the new imported data for this specific cell, but keep the old one. Others cells without focus work well.
    For example, originally I choose a "Monday" from the combobox with focus. When I import new data (by clicking some button), for instance "Tuesday", the new data doesn't show in the focused cell.
    So, how can I surrend the focus of this specific cell to other components, for instance, some button?

    In your action for your button, before you update your table with the imported information do the following:
    if (myTable.isEditing())
        myTable.getCellEditor().stopCellEditing();
    }

Maybe you are looking for

  • Edge Animation having troubles with iOS devices within Muse Site

    Hi All! I've been creating a mobile version of my website www.rinkdesigns.com and have it all complete. I created an animation/navigation bar within Adobe Edge Animate and imported it into Muse. It functions AMAZINGLY on my Nexus 4 (Android) in Chrom

  • Slide Shows on TV DVD Players

    I have old family photos, which I've scanned, loaded into PSE8, set dates, and created captions.  I've also organized them into albums.  Now I want to create a DVD slide show that my parents can play on their DVD without using a computer. Seems I nee

  • Problema Installazione Camera Raw e colori Lightroom 4?

    Salve a tutti. Sono italiano e non trovando un forum in italiano ho postato qui la domanda. Il mio problema è questo: ho una versione completa di Lightroom 4 e purtroppo quando carico i file RAW in formato RAF i colori sono sbiaditi e il programma mi

  • Iphone work on all networks

    Will we ever see an iphone that works on verizon?

  • Do a perl command from applescript

    I'd like to use Perl from AppleScript for text replacements. The snippet below works, however when the var haystackString starts to include apostrophes, this fails. I tried using AppleScript's "quoted form of" on haystackString however it fails I thi