Problem in event handling of combo box in JTable cell

Hi,
I have a combo box as an editor for a column cells in JTable. I have a event listener for this combo box. When ever I click on the JTable cell whose editor is combo box,
I get the following exception,
Exception occurred during event dispatching:
java.lang.NullPointerException
     at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.setDispatchComponent(Unknown Source)
     at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mousePressed(Unknown Source)
     at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
     at java.awt.Component.processMouseEvent(Unknown Source)
     at java.awt.Component.processEvent(Unknown Source)
     at java.awt.Container.processEvent(Unknown Source)
     at java.awt.Component.dispatchEventImpl(Unknown Source)
     at java.awt.Container.dispatchEventImpl(Unknown Source)
     at java.awt.Component.dispatchEvent(Unknown Source)
     at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
     at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
     at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
     at java.awt.Container.dispatchEventImpl(Unknown Source)
     at java.awt.Component.dispatchEvent(Unknown Source)
     at java.awt.EventQueue.dispatchEvent(Unknown Source)
     at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
     at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
     at java.awt.EventDispatchThread.run(Unknown Source)
Can any one tell me how to over come this problem.
Thanks,
Raghu

Here's an example of the model I used in my JTable. I've placed 2 comboBoxes with no problems.
Hope this helps.
public class FileModel5 extends AbstractTableModel
public boolean isEditable = false;
protected static int NUM_COLUMNS = 3;
// initialize number of rows to start out with ...
protected static int START_NUM_ROWS = 0;
protected int nextEmptyRow = 0;
protected int numRows = 0;
static final public String file = "File";
static final public String mailName = "Mail Id";
static final public String postName = "Post Office Id";
static final public String columnNames[] = {"File", "Mail Id", "Post Office Id"};
// List of data
protected Vector data = null;
public FileModel5()
data = new Vector();
public boolean isCellEditable(int rowIndex, int columnIndex)
// The 2nd & 3rd column or Value field is editable
if(isEditable)
if(columnIndex > 0)
return true;
return false;
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
public Class getColumnClass(int c)
return getValueAt(0, c).getClass();
* Retrieves number of columns
public synchronized int getColumnCount()
return NUM_COLUMNS;
* Get a column name
public String getColumnName(int col)
return columnNames[col];
* Retrieves number of records
public synchronized int getRowCount()
if (numRows < START_NUM_ROWS)
return START_NUM_ROWS;
else
return numRows;
* Returns cell information of a record at location row,column
public synchronized Object getValueAt(int row, int column)
try
FileRecord5 p = (FileRecord5)data.elementAt(row);
switch (column)
case 0:
return (String)p.file;
case 1:
return (String)p.mailName;
case 2:
return (String)p.postName;
catch (Exception e)
return "";
public void setValueAt(Object aValue, int row, int column)
FileRecord5 arow = (FileRecord5)data.elementAt(row);
arow.setElementAt((String)aValue, column);
fireTableCellUpdated(row, column);
* Returns information of an entire record at location row
public synchronized FileRecord5 getRecordAt(int row) throws Exception
try
return (FileRecord5)data.elementAt(row);
catch (Exception e)
throw new Exception("Record not found");
* Used to add or update a record
* @param tableRecord
public synchronized void updateRecord(FileRecord5 tableRecord)
String file = tableRecord.file;
FileRecord5 p = null;
int index = -1;
boolean found = false;
boolean addedRow = false;
int i = 0;
while (!found && (i < nextEmptyRow))
p = (FileRecord5)data.elementAt(i);
if (p.file.equals(file))
found = true;
index = i;
} else
i++;
if (found)
{ //update
data.setElementAt(tableRecord, index);
else
if (numRows <= nextEmptyRow)
//add a row
numRows++;
addedRow = true;
index = nextEmptyRow;
data.addElement(tableRecord);
//Notify listeners that the data changed.
if (addedRow)
nextEmptyRow++;
fireTableRowsInserted(index, index);
else
fireTableRowsUpdated(index, index);
* Used to delete a record
public synchronized void deleteRecord(String file)
FileRecord5 p = null;
int index = -1;
boolean found = false;
int i = 0;
while (!found && (i < nextEmptyRow))
p = (FileRecord5)data.elementAt(i);
if (p.file.equals(file))
found = true;
index = i;
} else
i++;
if (found)
data.removeElementAt(i);
nextEmptyRow--;
numRows--;
fireTableRowsDeleted(START_NUM_ROWS, numRows);
* Clears all records
public synchronized void clear()
int oldNumRows = numRows;
numRows = START_NUM_ROWS;
data.removeAllElements();
nextEmptyRow = 0;
if (oldNumRows > START_NUM_ROWS)
fireTableRowsDeleted(START_NUM_ROWS, oldNumRows - 1);
fireTableRowsUpdated(0, START_NUM_ROWS - 1);
* Loads the values into the combo box within the table for mail id
public void setUpMailColumn(JTable mapTable, ArrayList mailList)
TableColumn col = mapTable.getColumnModel().getColumn(1);
javax.swing.JComboBox comboMail = new javax.swing.JComboBox();
int s = mailList.size();
for(int i=0; i<s; i++)
comboMail.addItem(mailList.get(i));
col.setCellEditor(new DefaultCellEditor(comboMail));
//Set up tool tips.
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for mail Id list");
col.setCellRenderer(renderer);
//Set up tool tip for the mailName column header.
TableCellRenderer headerRenderer = col.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer)
((DefaultTableCellRenderer)headerRenderer).setToolTipText(
"Click the Mail Id to see a list of choices");
* Loads the values into the combo box within the table for post office id
public void setUpPostColumn(JTable mapTable, ArrayList postList)
TableColumn col = mapTable.getColumnModel().getColumn(2);
javax.swing.JComboBox combo = new javax.swing.JComboBox();
int s = postList.size();
for(int i=0; i<s; i++)
combo.addItem(postList.get(i));
col.setCellEditor(new DefaultCellEditor(combo));
//Set up tool tips.
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for post office Id list");
col.setCellRenderer(renderer);
//Set up tool tip for the mailName column header.
TableCellRenderer headerRenderer = col.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer)
((DefaultTableCellRenderer)headerRenderer).setToolTipText(
"Click the Post Office Id to see a list of choices");
}

Similar Messages

  • Problem with event handling

    Hello all,
    I have a problem with event handling. I have two buttons in my GUI application with the same name.They are instance variables of two different objects of the same class and are put together in the one GUI.And their actionlisteners are registered with the same GUI. How can I differentiate between these two buttons?
    To be more eloborate here is a basic definition of my classes
    class SystemPanel{
             SystemPanel(FTP ftp){ app = ftp};
             FTP app;
             private JButton b = new JButton("ChgDir");
            b.addActionListener(app);
    class FTP extends JFrame implements ActionListener{
               SystemPanel rem = new SystemPanel(this);
               SystemPanel loc = new SystemPanel(this);
               FTP(){
                       add(rem);
                       add(loc);
                       pack();
                       show();
           void actionPerformed(ActionEvent evt){
            /*HOW WILL I BE ABLE TO KNOW WHICH BUTTON WAS PRESSED AS THEY
               BOTH HAVE SAME ID AND getSouce() ?
               In this case..it if was from rem or loc ?
    }  It would be really helpful if anyone could help me in this regard..
    Thanks
    Hari Vigensh

    Hi levi,
    Thankx..
    I solved the problem ..using same concept but in a different way..
    One thing i wanted to make clear is that the two buttons are in the SAME CLASS and i am forming 2 different objects of the SAME class and then putting them in a GUI.THERE IS NO b and C. there is just two instances of b which belong to the SAME CLASS..
    So the code
    private JButton b = new JButton("ChgDir");
    b.setActionCommand ("1");
    wont work as both the instances would have the label "ChgDir" and have setActionCommand set to 1!!!!
    Actually I have an array of buttons..So I solved the prob by writting a function caled setActionCmdRemote that would just set the action commands of one object of the class differently ..here is the code
    public void setActionCommandsRemote()
         for(int i = 0 ; i <cmdButtons.length ; i++)
         cmdButtons.setActionCommand((cmdButtons[i].getText())+"Rem");
    This just adds "rem" to the existing Actioncommand and i check it as folows in my actionperformed method
         if(button.getActionCommand().equals("DeleteRem") )          
                        deleteFileRemote();
          else if(button.getActionCommand().equals("Delete") )
                     deleteFileLocal();Anyway thanx a milion for your help..this was my first posting and I was glad to get a prompt reply!!!

  • Having a combo box in a cell not to whole column

    I want to have a combo box in a cell of a table but not the whole column.Please help me in this .Its very important to our project

    Sorry , I don't want more space in cell.I want a combo box in a cell.But when i am setting the combo box it is applying to whole column and in every row i am getting a combobox .But i want to have a combo box in one row and a textfield in another row in the same column.
    Note : I am taking the input for a form in that i want a combo for background color ,font,size etc but i want a textfield for label .I think u have understood.
    thnx

  • Adding an event listener to combo box

    I am working on a mortgage calculator and I cannot figure out how to add an event listener to a combo box.
    I want to get the mortgage term and interest rate to calucate the mortgage using the combo cox. Here is my program.
    Modify the mortgage program to allow the user to input the amount of a mortgage
    and then select from a menu of mortgage loans: 7 year at 5.35%, 15 year at 5.50%, and
    30 year at 5.75%. Use an array for the different loans. Display the mortgage payment
    amount. Then, list the loan balance and interest paid for each payment over the term
    of the loan. Allow the user to loop back and enter a new amount and make a new
    selection, with resulting new values. Allow user to exit if running as an application
    (can't do that for an applet though).
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.text.NumberFormat;
    import java.util.Locale;
    //creates class MortgageCalculator
    public class MortgageCalculator extends JFrame implements ActionListener {
    //creates title for calculator
         JPanel row = new JPanel();
         JLabel mortgageCalculator = new JLabel("MORTGAGE CALCULATOR", JLabel.CENTER);
    //creates labels and text fields for amount entered          
         JPanel firstRow = new JPanel(new GridLayout(3,1,1,1));
         JLabel mortgageLabel = new JLabel("Mortgage Payment $", JLabel.LEFT);
         JTextField mortgageAmount = new JTextField(10);
         JPanel secondRow = new JPanel();
         JLabel termLabel = new JLabel("Mortgage Term/Interest Rate", JLabel.LEFT);
         String[] term = {"7", "15", "30"};
         JComboBox mortgageTerm = new JComboBox(term);
         JPanel thirdRow = new JPanel();
         JLabel interestLabel = new JLabel("Interest Rate (%)", JLabel.LEFT);
         String[] interest = {"5.35", "5.50", "5.75"};
         JComboBox interestRate = new JComboBox(interest);
         JPanel fourthRow = new JPanel(new GridLayout(3, 2, 10, 10));
         JLabel paymentLabel = new JLabel("Monthly Payment $", JLabel.LEFT);
         JTextField monthlyPayment = new JTextField(10);
    //create buttons to calculate payment and clear fields
         JPanel fifthRow = new JPanel(new GridLayout(3, 2, 1, 1));
         JButton calculateButton = new JButton("CALCULATE PAYMENT");
         JButton clearButton = new JButton("CLEAR");
         JButton exitButton = new JButton("EXIT");
    //Display area
         JPanel sixthRow = new JPanel(new GridLayout(2, 2, 10, 10));
         JLabel displayArea = new JLabel(" ", JLabel.LEFT);
         JTextArea textarea = new JTextArea(" ", 8, 50);
    public MortgageCalculator() {
         super("Mortgage Calculator");                     //title of frame
         setSize(550, 350);                                             //size of frame
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         Container pane = getContentPane();
         GridLayout grid = new GridLayout(7, 3, 10, 10);
         pane.setLayout(grid);
         pane.add(row);
         pane.add(mortgageCalculator);
         pane.add(firstRow);
         pane.add(mortgageLabel);
         pane.add(mortgageAmount);
         pane.add(secondRow);
         pane.add(termLabel);
         pane.add(mortgageTerm);
         pane.add(thirdRow);
         pane.add(interestLabel);
         pane.add(interestRate);
         pane.add(fourthRow);
         pane.add(paymentLabel);
         pane.add(monthlyPayment);
         monthlyPayment.setEnabled(false);
         pane.add(fifthRow);
         pane.add(calculateButton);
         pane.add(clearButton);
         pane.add(exitButton);
         pane.add(sixthRow);
         pane.add(textarea); //adds texaarea to frame
         pane.add(displayArea);
         setContentPane(pane);
         setVisible(true);
         //Adds Listener to buttons
         calculateButton.addActionListener(this);
         clearButton.addActionListener(this);
         exitButton.addActionListener(this);
         mortgageTerm.addActionListener(this);
         interestRate.addActionListener(this);
    public void actionPerformed(ActionEvent event) { 
         Object command = event.getSource();
         JComboBox mortgageTerm = (JComboBox)event.getSource();
         String termYear = (String)mortgageTerm.getSelectedItem();
    if (command == calculateButton) //calculates mortgage payment
         int year = Integer.parseInt(mortgageTerm.getText());
         double rate = new Double(interestRate.getText()).doubleValue();
         double mortgage = new Double(mortgageAmount.getText()).doubleValue();
         double interest = rate /100.0 / 12.0;
         double monthly = mortgage *(interest/(1-Math.pow(interest+1,-12.0 * year)));
                   NumberFormat myCurrencyFormatter;
                   myCurrencyFormatter = NumberFormat.getCurrencyInstance(Locale.US);
                   monthlyPayment.setText(myCurrencyFormatter.format(monthly));
         if(command == clearButton) //clears all text fields
                   mortgageAmount.setText(null);
                   //mortgageTerm.setText(null);
                   //interestRate.setText(null);
                   monthlyPayment.setText(null);
              if(command == exitButton) //sets exit button
                        System.exit(0);
         public static void main(String[] arguments) {
              MortgageCalculator mor = new MortgageCalculator();

    The OP already did this to both JComboBoxes.
    mochatay, here is a new actionPerformed method for you to use.
    I've improved a few things here and there...
    1) You can't just cast the ActionEvent's source into a JComboBox!
    What if it was a JButton that fired the event? Then you would get ClassCastExceptions (I'm sure you did)
    So check for all options, what the source of the ActionEvent actually was...
    2) You can't assume the user will always type in valid data.
    So enclose the Integer and Double parse methods in try-catch brakcets.
    Then you can do something when you know that the user has entered invalid input
    (like tell him/her what a clumsy idiot they are !)
    3) As soon as user presses an item in any JComboBox, just re-calculate.
    I did this here by programmatically clicking the 'Calculate' button.
    Alternatively, you could have a 'calculate' method, which does everything inside the
    if(command==calculateButton) if-block.
    This will be called when:
    a)calculateButton is pressed
    b)when either of the JComboBoxes are pressed.
    public void actionPerformed (ActionEvent event)
            Object command = event.getSource ();
            if (command == calculateButton) //calculates mortgage payment
                int year = 0;
                double rate = 0;
                double mortgage = 0;
                double interest = 0;
                /* If user has input invalid data, tell him so
                and return (Exit from this method back to where we were before */
                try
                    year = Integer.parseInt (mortgageTerm.getSelectedItem ().toString ());
                    rate = new Double (interestRate.getSelectedItem ().toString ()).doubleValue ();
                    mortgage = new Double (mortgageAmount.getText ()).doubleValue ();
                    interest = rate / 100.0 / 12.0;
                catch (NumberFormatException nfe)
                    /* Display a message Dialogue box with a message */
                    JOptionPane.showMessageDialog (this, "Error! Invalid input!");
                    return;
                double monthly = mortgage * (interest / (1 - Math.pow (interest + 1, -12.0 * year)));
                NumberFormat myCurrencyFormatter;
                myCurrencyFormatter = NumberFormat.getCurrencyInstance (Locale.US);
                monthlyPayment.setText (myCurrencyFormatter.format (monthly));
            else if (command == clearButton) //clears all text fields
                /* Better than setting it to null (I think) */
                mortgageAmount.setText ("");
                //mortgageTerm.setText(null);
                //interestRate.setText(null);
                monthlyPayment.setText ("");
            else if (command == exitButton) //sets exit button
                System.exit (0);
            else if (command == mortgageTerm)
                /* Programmatically 'clicks' the button,
                As is user had clicked it */
                calculateButton.doClick ();
            else if (command == interestRate)
                calculateButton.doClick ();
            //JComboBox mortgageTerm = (JComboBox) event.getSource ();
            //String termYear = (String) mortgageTerm.getSelectedItem ();
        }Hope this solves your problems.
    I also hope you'll be able to learn from what I've indicated, so you can use similar things yourself
    in future!
    Regards,
    lutha

  • Problem in event handling using oo abap code

    Hi,
    My requirement is i need to disply 3 blocks in ALV format.I have done that.Now my problem is if i double click on aufnr of the first block, it should call the transaction code. I have written the code in oo abap but i have used function modules for ALV.Now my doubt is 'How to write an event  once the user double click on the particular field of the first block, it should call the tcode " using object oriented code.
    How to populate the heading for each block using oo abap code.
    Thanks & Regards
    Anus

    hi.....
    Use Double_click event handler method of class cl_gui_alv_grid of first block....
    if not solved .
    Send me Your program lines ...........
    Best Regards
    Prabhakar

  • Drop down menu or combo box in jtable

    Hi there I nee urgent help I have a jtable and I am collecting information to populate the table dynamically, the problem is I some of the strings that populate certain cells is longer the the width of the cell in a particular column, I thought I could use a combo box and split the strings up so I could have some type of drop down menu showing the information, but when I populate the combo box and instantiate the defaultcell renderer with the combobox it sets all cells in that column with the same information I would like to have it displaying the actual information for every row within that column
    or if you can give me any ideas as to how I can avoid this happening or maybe an alternative method of showing these long strings in the table some kind of drop down.
    Kind Regards Michael

    the problem is I some of the strings that populate certain cells is longer the the width of the cell in a particular column,Set a tooltip to display the entire text of the cell. Here is a simple example;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TableToolTip extends JFrame
         public TableToolTip()
              Object[][] data = { {"1234567890qwertyuiop", "A"}, {"2", "B"}, {"3", "C"} };
              String[] columnNames = {"Number","Letter"};
              JTable table = new JTable(data, columnNames)
                   public String getToolTipText( MouseEvent e )
                        int row = rowAtPoint( e.getPoint() );
                        int column = columnAtPoint( e.getPoint() );
                        Object value = getValueAt(row, column);
                        return value == null ? null : value.toString();
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableToolTip frame = new TableToolTip();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.setSize(150, 100);
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }If you want to get fancier than you could set the tooltip text only when the width of the text is greater than the width of the column. Here is an example of this is done with a text field. You would need to modify the code to refer the to table for the text string and the TableColumn for the width.:
    JTextField textField = new JTextField(15)
         public String getToolTipText(MouseEvent e)
              FontMetrics fm = getFontMetrics( getFont() );
              String text = getText();
              int textWidth = fm.stringWidth( text );
              return (textWidth > getSize().width ? text : null);
    textField.setToolTipText(" ");
    I thought I could use a combo box and split the strings up so I could have some type of drop down menu showing the informationIf you want to proceed with this approach then check out this posting:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=637581

  • Event Handler for a JComboBox in JTable

    Hi,
    I am using a JTable with one column having JComboBox as CellEditor, I Want to handle event for jcomboBox such that if I am selecting any item from JcomboBox item , i check if there is any field before that in the Jtable Cell if yes then I am setting it to null or the previous value. I have implemented CellEditorListener to it but it is not working fine, so if anyone can please help me out..

    If I read you right, you want to use a multiple keystroke combo box as an editor in a JTable?
    If you create the JComboBox as you would like it and then install it as an editor in the column(s) JTable the editor will work like the JComboBox
    Example:
    //- you would have that keyselection Manager class
    // This key selection manager will handle selections based on multiple keys.
    class MyKeySelectionManager implements JComboBox.KeySelectionManager {    ....    };
    //- Create the JComboBox with the multiple keystroke ability
    //- Create a read-only combobox
    String[] items = {"Ant", "Ape", "Bat", "Boa", "Cat", "Cow"};
    JComboBox cboBox = new JComboBox(items);
    // Install the custom key selection manager
    cboBox.setKeySelectionManager(new MyKeySelectionManager());
    //- combo box editor for the JTable
    DefaultCellEditor cboBoxCellEditor = new DefaultCellEditor(cboBox);
    //- set the editor to the specified COlumn in the JTable - for example the first column (0)
    tcm.getColumn(0).setCellEditor(cboBoxCellEditor); Finally, it may be necessary to to put a KeyPressed listener for the Tab key, and if you enter the column that has the JComboBox:
    1) start the editting
    table.editCellAt(row, col);2) get the editor component and cast it into a JComboBox (in this case)
    Component comp = table.getEditorComponent();
    JComboBox cboComp = (JComboBox) comp;3) give this compent the foucus to do its deed     
    cboComp.requestFocus();Hope this helps!
    dd

  • Updating combo box in JTable

    While updating combo box in a JTable, after updating the first row when pointer (logical) goes to the second row it says value already exists. Kindly let me know if anyone has the solution for the same.

    While updating combo box in a JTable, after updating the first row when pointer (logical) goes to the second row it says value already exists. Kindly let me know if anyone has the solution for the same.

  • Combo Box in JTable

    Is there a way to make one column in a JTable a ComboBox so that user can choose between 2-3 items?
    Any code help would be appreciated.
    Mdev

    Here are just some code snippets, sorry i didn't tidy them up.
    //here is the initialization of the comboBox column and get data from db
    public void initComboColumn(TableColumn col, String query) {
      JComboBox comboBox = new JComboBox();
      Vector columnResults = DatabaseUtilities.getComboResults(query, true);
      try {
        if (! (columnResults.contains("R"))) {
          columnResults.addElement("R");
        if (! (columnResults.contains("N"))) {
          columnResults.addElement("N");
        if (! (columnResults.contains("B"))) {
          columnResults.addElement("B");
        comboBox.setModel(new ResultSetComboBoxModel(columnResults));
        col.setCellEditor(new DefaultCellEditor(comboBox));
        DefaultTableCellRenderer renderer =
            new DefaultTableCellRenderer();
        renderer.setToolTipText("Click for combo box & choose data type");
        col.setCellRenderer(renderer);
        //Set up tool tip for the sport column header.
        TableCellRenderer headerRenderer = col.getHeaderRenderer();
        if (headerRenderer instanceof DefaultTableCellRenderer) {
          ( (DefaultTableCellRenderer) headerRenderer).setToolTipText(
              "Click to see a list of choices");
      catch (Exception e) {
        e.printStackTrace();
    //ResultSetComboBoxModel
    import javax.swing.*;
    import java.sql.*;
    import java.util.Vector;
    public class ResultSetComboBoxModel extends ResultSetListModel
        implements ComboBoxModel
        protected Object selected = null;
        public ResultSetComboBoxModel(Vector columnResults) throws Exception {
            super(columnResults);
        public Object getSelectedItem() {
          return selected;
        public void setSelectedItem(Object o) {
            if(o==null)
              selected = o;
            else{
              String value = (String) o;
              selected = (Object)(value.substring(0,value.lastIndexOf("  //  ")));
    //ResultSetListModel
    import javax.swing.*;
    import java.util.*;
    import java.sql.*;
    public class ResultSetListModel extends AbstractListModel {
        List values = new ArrayList();
        public ResultSetListModel(Vector columnResults) throws Exception {
          for(Iterator item = columnResults.iterator();item.hasNext();){
            String[] value  = (String[])item.next();
            values.add(value[0] + "  //  " + value[1]);
        public int getSize() {
            return values.size();
        public Object getElementAt(int index) {
          return values.get(index);
    }Hope this helps.
    Regards,
    Pippen

  • Enable / disable combo box in datagrid cell

    I have a datagrid with 8 columns 2 check boxes a text box and
    5 combo boxes. I am trying to disable the combo boxes if the first
    check box is not checked. So far I am able to disable the entire
    column with the combo box in it, but what i am trying to achieve is
    if the check box is false then the 5 combo boxes are to be
    disabled.
    So what I am asking in a nutshell is is there a way to enable
    or disable particular cells in a datagrid ?
    Example
    of what I have already done
    Any suggestions will be gratefully received.

    I put the following code in that I took from samples:
    Bindable]public var test:ArrayCollection;
    private  
    function init():void
    test =
    new ArrayCollection([{label:"High", data:"high"},{label:
    "Medium", data:"medium"},{label:
    "Low", data:"low"}]) 
    Then in the mxml:
    <mx:DataGridColumn 
    headerText="From Fiscal Period">
    <mx:itemRenderer>
    <mx:Component>
    <mx:ComboBox dataProvider="{test}">
    </mx:ComboBox>
    </mx:Component>
    </mx:itemRenderer>
    </mx:DataGridColumn>
    I still get the same error: 1120: Access of undefined property test.

  • Event handling of JComboBox outside a JTable

    Hi to All,
    I've a question about JTables and JComboBoxes... I'm working on a application which holds a JTable and several JButtons and JCombBoxes. When the user clicks on a cell in the JTable, this cell will get the focus and the text will be highlighted. An action will be performed when the user clicks on a JButton (this just works fine). When the user clicks on a JComboBox also an action must be performed... but this won't work. I guess it won't work because of the JComboBox will draw a popup, and this popup will be cover the cell with the focus...
    I could not catch any event of the JComboBox...
    How can I check for a click on a JComboBox when an other component (JTable cell) has the focus?
    Thnx,

    Hi Swetha,
    Button controls in a table are available only in version 2.0 of the .NET PDK.
    In order to use Button in a table and handle its events u will have to upgrade.
    Further information about using input controls in a table is available in the How to section of the PDK documentation.
    Thanks, Reshef

  • Capturing events from a JCheckBox in a JTable cell

    I am trying to capture item state changed event from a JCheckbox in a JTable. When user selects checkbox I do insert in database and on deselect I do delete from database. The item state changed event is not firing correctly...can you please tell me what I am doing wrong. My JTable uses CustomModel which is used by many other apps. So I can not really modify CustomModel only to work with my JTable. Here is my code.
    public class MyClass extends JPanel
    .....some code to add panel, jscorollpane, etc.
    ResultSet res;
    GUI gui; //Custom Class to deal with different GUI layouts
    JTable myJTable = new JTable();
    GUI.CustomModel custModel;
    public void init()
         displayJTable();
    attachCheckBoxListeners();
    private void displayForms()
         res = //resultset from DB
    Vector cols = new Vector(10);
    cols.addElement(new Integer(1);
    gui.DisplayResultSetinTabel(res, myJtable, cols, null);
    custModel= (GUI.CustomModel) ((TableSorter) myJTable.getModel()).getModel();
    custModel.setEditableColumn(0, true);
    //Attach CheckBox Listener to all the checkbox in JTable
    private void attachCheckBoxListeners()
    for(int row = 0; row< myJTable.getRowCount(); row++)
    Object val = cm.getValueAt(row, 0);
    final JCheckBox jcb = (JCheckBox) gridForms.getCellEditor(row, 0).getTableCellEditorComponent(gridForms, val, true, row, 0);
    jcb.addItemListener( new java.awt.event.ItemListener() // Add Item Listener to trap events
    public void itemStateChanged(java.awt.event.ItemEvent event)
                   if(myJtable.getSelectedRow() == -1) // if no row is selected in table return
                        return;
                   try               
                   if (res.absolute(myJtable.getSelectedRow())+1))
         if(jcb.isSelected())
    saveData();();      
         else
    deleteData();
         catch(Exception e)
    System.out.println("ERROR ");
    } //end of AttachCheckBoxListeners ()
    private void SaveData() {}
    private void DeleteData() {}
    Okay....the problem is when JCheckBox state is changed (by user) from Selected to Deselected itemStateChanged() is fired and it does delete from database. then again itemStateChanged() called it detects Jcheckbox as selected and does inseret in database. On Jtable gui...that checkbox is still shown as desected.
    Please tell me what is going on here.....
    Thank you.

    In short - never listen to low-level events from editorComponents (low-level meaning everything below - and most of the time including - a editingStopped/editingCancelled of the cellEditor). Your problem belongs to the model realm - save if a cell value is changed - so solve it in the model realm by listening to event from the tableModel and trigger your business logic when you detect a change in that particular cell value.
    Greetings
    Jeanette

  • Problems with event handling in JmenuItem

    Hello:
    I'm trying to handle an event for a menuItem and tool bar item: with this code:
    newBallotAction = new AbstractAction("newBallot")
    public void actionPerformed(ActionEvent e)
    try{
    System.out.println("MainWindow newBallotAction");
    Ballot ballot = new Ballot();
    System.out.println("MainWindow newBallotAction 2nd");
    DDNewBallotWindow ddNewBallotWindow = new DDNewBallotWindow(ballot);
    if (ballot != null) // <ballotName>, <ballotOptionsNumber> , <ballotOption1>, <ballotOption2>, .., <ballotOption(optionsNumber)>
    brothers.msgToBrothers("<Ballot>" + "<origin>" + myName + "</origin>"+ ballot.toRep() +"</Ballot>" , myName);
    else
    System.out.println("MainWindow ballot null");
    }catch(Exception f){
    System.out.println("MainWindow newBallotAction exception" + e);
    JMenuItem ballotMIDdMenu = new JMenuItem("New Ballot");
    ballotMIDdMenu = fileMenu.add(newBallotAction);
    ddMenu.add(ballotMIDdMenu);
    It produces the next exception:
    MainWindow newBallotAction exceptionjava.awt.event.ActionEvent[ACTION_PERFORMED,cmd=newBallot] on javax.swing.JMenu$2[,1,49,137x21,alignmentX=null,alignmentY=null,border=javax.swing.plaf.metal.MetalBorders$MenuItemBorder@55a338,flags=264,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=2,bottom=2,right=2],paintBorder=true,paintFocus=false,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=newBallot]
    It's really complex ... I'm desperado ;)
    Thanks in advance, Nacho.

    Hi,
    The exception is propably occuring in the Ballot() constructor (which you didn't post).
    And, as dukeman already mentionned, you are printing out the ActionEvent object and not the Exception itself.

  • Problem about event handling or dispatching

    I created a JFrame with a JButton in it. A keyListener is add to the jframe.
    Key events can be catched if JDK1.3.1_08 is employed. However, it doesn't work if JDK1.4.1_02 is empolyed. Can anyone tell me the problem? Thanks a lot!
    The following is the source code:
    public class drawa extends JFrame implements KeyListener
    public static void main(String[] args) {  
         drawa frame = new drawa();
    public drawa() {   
         super("drawa");
         Container c=getContentPane();
         c.setLayout(null);
         JButton jb=new JButton("L");
         jb.setSize(80,40);
         c.add(jb);     
         addKeyListener(this);
         setSize(500,450);          
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setVisible(true);          
    public void keyPressed(KeyEvent evt){
         System.out.println("a");
    public void keyTyped(KeyEvent evt){}
    public void keyReleased(KeyEvent evt){}

    Your frame must return true for isFocusable ().
    Kind regards,
      Levi

  • Working with Combo boxes in JTable in swings

    Hello everyone,
    I am working on swing components. We are designing a swing based platform for our company. I have a case where i have to use comboboxes in a jtable. I have seen a lot of topics on this but i have an issue with that. We have to implement a type ahead feature in these comboboxes where if we type any key the items in the table which start with that alphabet or sybol are selected. We can see this by default in regular comboboxes but i have been unable to implement this in the jtable. I have tried various ways like adding listeners etc. and none of them are working. This is my code for the cell renderers for these comboboxes
    public 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());
    setSelectedItem(value);
    return this;
    public class MyComboBoxEditor extends DefaultCellEditor {
    public MyComboBoxEditor(Vector items) {
    super(new JComboBox(items));
    Can anyone who has faced a similar issue help me regarding this.
    Thanks in advance
    Edited by: bharat20 on Nov 14, 2007 6:58 AM

    Hi,
    Have you tried the Swing forums at java.sun.com? This is the Java Studio Enterprise IDE Forum, so you probably won't get much response here.
    http://forum.java.sun.com/category.jspa?categoryID=7
    Also, what IDE tools are you using?
    R

Maybe you are looking for

  • How to get the "link" HTML.attribute

    What are the HTML.attribute that could contain a link ? The most common are HREF and SRC but there are too : ACTION, BGCOLOR ... and attribute that doesn't contain links like width ... Is there anyway to know the attributes that can contain links, or

  • Can I embed java app in flash (mp3 recorder)

    I need to provide an mp3 recorder from the user's sound card functionality to a flash application. It will be strictly a web app hosted on a server, not an install. User's may or may not have admin priviledges. I am mostly a vb guy so I was wondering

  • Apple pro res 422 file consuming more space than usual

    hi everyone! I've been  working with FCP 7 since 2008 and at the same time I started working with Canon T2 from 2 years ago and I haven't had any problems with my FCP workflow files, editing and output used to be H. 264 based files until I started to

  • Column in report to link to e-mail system

    My select is: select emp_name, emp_id, 'mailto:'|| emp_email email; I made the email column hidden. What do I need to do to make a link to the emp_name bring up the email system (with the employees e-mail in the 'to:' field)? I'm not sure how to get

  • CS6 Much Slower than CS5.5

    I installed Premiere Pro CS6 for Mac and moved an existing project from CS5.5.  The clips are all After Effects compositions, some with elaborate effects. I imported them into AE6 from AE5.5 prior to bringing them into CS6 so they would interact betw