Friday, December 27, 2013

TableCellEditor that implements ItemListener

This sample code uses the JComboBox as the component.

public class MyComboBoxEditor extends DefaultCellEditor implements PopupMenuListener, ItemListener {
        Component comp = null;
        int theRow = 0;
        int theCol = 0;
        public MyComboBoxEditor(JComboBox jcb) {
            super(jcb);
        }

        @Override
        public Component getTableCellEditorComponent(
                JTable table, Object value, boolean isSelected, int row, int column) {

            //critical to set the row and col before calling
            //super.getTableCellEditorComponent which fires the ItemListener
            //for the ItemListener to work properly not using previous row and col.
            theRow = row;
            theCol = column;
            comp = super.getTableCellEditorComponent(table, value, isSelected, row, column);
         
            ((JComboBox)comp).removeItemListener(this);
            ((JComboBox)comp).addItemListener(this);
            ((JComboBox)comp).removePopupMenuListener(this);
            ((JComboBox)comp).addPopupMenuListener(this);
         
            return comp;
        }
     
        @Override
        public void popupMenuCanceled(PopupMenuEvent e){
            table.stopCellEditing();
        }
   
        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            table.stopCellEditing();
        }
     
        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
        }
     
        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e == null) {
                return;
            }
            JComboBox source = (JComboBox) e.getSource();
            if (e.getStateChange() == ItemEvent.SELECTED) {
                  Object obj = e.gtItem();
                  //table.editCellAt(theRow, theCol); need this because of the calling table.stopCellEditing() above
                  //code for modifying the JTable related to theRow and theCol
           }
           e = null
      }
}

----------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

No comments:

Post a Comment