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.

Similar Messages

  • 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");
    }

  • 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

  • Programmatically update Combo box won't update its Local variable

    Hello all,
    I followed a tutorial from NI website and programmatically edit items in a combo box. It worked successfully but not for the Local variables. Local variables still retain items that it had before.
    Any suggestions ?
    Thanks !
    Solved!
    Go to Solution.

    You need to programmatically update the value property in order to change what the local variable will return, the value that you will wire doesn't have to match with one of the Strings[] array.
    Perhaps you need to do something like this to update your value to change from "Two" to "Five".

  • 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

  • Update Combo box choice

    I have written the below code. When "Equipment1_combo" is selected, the respective choice will be update into the "Equipment1_pcs". E.g. if I chose "Racket", it show the quantity from 0 to 12 (assume that the equipment_inventory dB have 12 as quantity of racket).
    <%
    Connection dbcon2;
    Statement statement2;
    Statement statement3;
    ResultSet rs2;
    ResultSet rs3;
    //connect to DB
    try
    String driver2 = "com.mysql.jdbc.Driver";
    String dbURL2 = "jdbc:mysql://localhost/fyp";
    Class.forName(driver2).newInstance();
    dbcon2 = DriverManager.getConnection(dbURL2);
    System.out.println("Connection to database is successful");
    catch(ClassNotFoundException e)
    System.out.println("Database driver could not be found.");
    System.out.println(e.toString());
    throw new UnavailableException(this, "Database driver class not found");
    catch(SQLException e)
    System.out.println("Error connecting to the database.");
    System.out.println(e.toString());
    throw new UnavailableException("Cannot connect to the database");
    statement2 = dbcon2.createStatement();
         rs2 = statement2.executeQuery("SELECT DISTINCT CATEGORY from EQUIPMENT_INVENTORY ORDER BY CATEGORY ASC");
         statement3 = dbcon2.createStatement();
         rs3 = statement3.executeQuery("SELECT QUANTITY from EQUIPMENT_INVENTORY where CATEGORY='"+request.getParameter("Equipment1_combo")+"' ");%>
    <p><b>Reserve Equipment </b></p>
    <p><b><i>Equipment 1</i></b>   
    <select name="Equipment1_combo">
    <% while (rs2.next()) {%>
    <option value = "<%=rs2.getString("Category")%>"><%=rs2.getString("Category")%></option>
    <%}%>
    </select>    No. of pieces   
    <select name="Equipment1_pcs">
    <% while (rs3.next()) {%>
    <option value = "<%=rs3.getString("Quantity")%>"><%=rs3.getString("Quantity")%></option>
    <%}
    rs3.close();
    %>
    </select></p>

    Right then.
    JSP is a server side language. All the code gets run at the server, and returned to the client as an HTML page. The only method of communication you have to the server is by submitting an html form.
    Therefore jsp code can not react to events on the form such as selecting an item from the list directly.
    There are 2 options
    1 - javascript - handles client side interaction with a web page - use javascript/vbscript to change the values in the combo.
    2 - when they select an item in the list, resubmit the form with that parameter, and generate the jsp accordingly (ie reload the page)
    This is not an uncommon question. Do a quick forum search and you come up with plenty of related posts
    Check out these links
    http://onesearch.sun.com/search/developers/index.jsp?col=devforums&qp=&qt=combo+jsp+javascript+select+dynamic
    http://forum.java.sun.com/thread.jsp?forum=54&thread=203309
    http://forum.java.sun.com/thread.jsp?forum=45&thread=145694

  • 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

  • JTable & Combo Box

    Hello
    I have 2 combo box in the Jtable. Whenever there is something selected in the first drop down i have to repopulate the second combo box.
    JTable.populateData(ArrayList);
    Column renderer /editor
    TableColumn column1 = tablePane.getTable().getColumnModel().getColumn(
    1);
    columnn1.setCellEditor(new ComboBoxCellEditor(this));
    column1.setCellRenderer(new ComboBoxCellRenderer(this));
    TableColumn column2 = tablePane.getTable().getColumnModel().getColumn(
    2);
    column2.setCellEditor(new ComboBoxCellEditor(this));
    column2.setCellRenderer(new ComboBoxCellRenderer(this));
    How do i repopulate the data in 2nd combo box.

    It sounds like the combobox can be different for every row based on the value in another column in the row, therefore you need to dynamically change the editor for each row. This can be done by overriding the getCellEditor() method:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableComboBoxByRow extends JFrame
        ArrayList editors = new ArrayList(3);
        public TableComboBoxByRow()
            // Create the editors to be used for each row
            String[] items1 = { "Red", "Blue", "Green" };
            JComboBox comboBox1 = new JComboBox( items1 );
            DefaultCellEditor dce1 = new DefaultCellEditor( comboBox1 );
            editors.add( dce1 );
            String[] items2 = { "Circle", "Square", "Triangle" };
            JComboBox comboBox2 = new JComboBox( items2 );
            DefaultCellEditor dce2 = new DefaultCellEditor( comboBox2 );
            editors.add( dce2 );
            String[] items3 = { "Apple", "Orange", "Banana" };
            JComboBox comboBox3 = new JComboBox( items3 );
            DefaultCellEditor dce3 = new DefaultCellEditor( comboBox3 );
            editors.add( dce3 );
            //  Create the table with default data
            Object[][] data =
                 {"Color", "Red"},
                 {"Shape", "Square"},
                 {"Fruit", "Banana"},
                 {"Plain", "Text"}
            String[] columnNames = {"Type","Value"};
            DefaultTableModel model = new DefaultTableModel(data, columnNames);
            JTable table = new JTable(model)
                //  Determine editor to be used by row
                public TableCellEditor getCellEditor(int row, int column)
                    if (column == 1 && row < 3)
                        return (TableCellEditor)editors.get(row);
                    else
                        return super.getCellEditor(row, column);
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
        public static void main(String[] args)
            TableComboBoxByRow frame = new TableComboBoxByRow();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
    }

  • Editable Combo box in a JTable

    Hi,
    Is it possible to have an editable combo Box in a JTable with an item Listener attached to the combo Box?
    Based on whatever value the user enters in that column that is rendered as a combo Box(editable) i should be able to do some validation. Is this possible?
    Thanks in advance for your time and patience.
    Archana

    Here's a start:
    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");
    }

  • Combo Box in a JTable not appearing

    Hi Swing,
    I have a snippet of code that I took from the Swing guide for JTables that adds a JComboBox into the 3rd column in the table. However, the ComboBox doesnt appear?
    Can anyone see what is going wrong? Code is below:- I can post more if needed:-
         public void addTable() {
              tableModel = new MyTableModel(rows,columns);
              relationTable = new JTable(tableModel);
           //Set up the editor for the sport cells.
            TableColumn sportColumn = table.getColumnModel().getColumn(2);                                              
            JComboBox allStaff = new JComboBox();
            allStaff.addItem("Snowboarding");
            allStaff.addItem("Rowing");
            allStaff.addItem("Knitting");
            allStaff.addItem("Speed reading");
            allStaff.addItem("Pool");
            allStaff.addItem("None of the above");
            sportColumn.setCellEditor(new DefaultCellEditor(allStaff));
              // set so only one row can be selected at once
              relationTable.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
              relationTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              // add to pane:-
              JScrollPane scrollPane3 = new JScrollPane(relationTable);
              scrollPane3.setBounds(X,Y,Z,W);
              getContentPane().add(scrollPane3 );
         }Cheers

    hi
    look I will give u a simple code I created based on your combo box
    enjoy (:
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    public class TablCo extends JPanel {
    static JFrame frame;
    JTable table;
    DefaultTableModel tm;
    public TablCo() {
    super(new BorderLayout());
    JPanel leftPanel = createVerticalBoxPanel();
    //Create a table model.
    tm = new DefaultTableModel();
    tm.addColumn("Column 0");
    tm.addColumn("Column 1");
    tm.addColumn("Column 2");
    tm.addColumn("Column 3");
    tm.addRow(new String[]{"01", "02", "03", "Snowboarding"});
    tm.addRow(new String[]{"04 ", "05", "06", "Snowboarding"});
    tm.addRow(new String[]{"07", "08", "09", "Snowboarding"});
    tm.addRow(new String[]{"10", "11", "12", "Snowboarding"});
    //Use the table model to create a table.
    table = new JTable(tm);
              //insert a combo box in table
              TableColumn sportColumn = table.getColumnModel().getColumn(3);
              JComboBox allStaff = new JComboBox();
                   allStaff.addItem("Snowboarding");
                   allStaff.addItem("Rowing");
                   allStaff.addItem("Knitting");
                   allStaff.addItem("Speed reading");
                   allStaff.addItem("Pool");
                   allStaff.addItem("None of the above");
              //DefaultCellEditor dce = new DefaultCellEditor(allStaff);
              sportColumn.setCellEditor(new DefaultCellEditor(allStaff));
              JScrollPane tableView = new JScrollPane(table);
    tableView.setPreferredSize(new Dimension(300, 100));
              leftPanel.add(createPanelForComponent(tableView, "JTable"));
              JFrame.setDefaultLookAndFeelDecorated(true);
              //Create and set up the window.
              frame = new JFrame("BasicDnD");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Create and set up the content pane.
              frame.setContentPane(leftPanel);
              //Display the window.
              frame.pack();
              frame.setVisible(true);
              protected JPanel createVerticalBoxPanel() {
              JPanel p = new JPanel();
              p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS));
              p.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
              return p;
              public JPanel createPanelForComponent(JComponent comp,
              String title) {
              JPanel panel = new JPanel(new BorderLayout());
              panel.add(comp, BorderLayout.CENTER);
              if (title != null) {
              panel.setBorder(BorderFactory.createTitledBorder(title));
              return panel;
    public static void main(String[] args) {
         new TablCo();
    }

  • Combo Box Valid Values Update

    Hi All,
    I'm developing a Form which has BP Code and a ComboBox which, after entering a valid Supplier in the BPCode EditText, updates the ComboBox with the Supplier Catalog Numbers of all the Items where the CardCode (in OITM) matches the BPCode.  I have this working for the first change of BPCode but when the BPCode changes I want to update the ComboBox ValidValues.  I have tried many methods but cannot remove the ValidValues which are already there.  I have tried linking the ComboBox to a DataTable, clearing the DataTable and rebinding but this doesn't seem to work either.
    Any help on removing ValidValues from a list when I don't know what is already there (as the VV list is now out of scope) or adding a data bound ComboBox would be most appreciated.
    Thanks in anticipation,
    David

    Hi David,
    Try following
            'get the reference to the state combo box
            oCombo = oForm.Items.Item("combo box unique id").Specific
            'remove existing items if any
            'before adding new items
            For Flag = 0 To oCombo.ValidValues.Count - 1
                oCombo.ValidValues.Remove(0, SAPbouiCOM.BoSearchKey.psk_Index)
            Next
    After this, use a recordset or datatable to retrieve the records, and than a loop to add valid values to the combo box.
    Rahul

  • Combo box list update or insert restriction

    Dear all,
    I have a list item which type is combo box.
    it shows the Departments list from the department table at run time.
    i populate at through a procedure at runtime.
    problem
    the user could update the list by writing something into it.
    i want to force the user to just select a value from the list, not update or insert.
    i change the properties of the list item which prevent insertion or updation,
    but it disable the selection from the list as well.
    how to prevent the user to write something in the combo box list while giving him the
    selection authority using the combo box list item?
    Thanks and Regards

    thank you dear,
    but i want to use the combo box instead.
    for popup list there is a problem of the null value,
    you must assign a value to the popup list and set its required property to true for doing so.
    and the combo box do not need this. and my desired functionality require it.
    Edited by: Muhammad on Feb 28, 2010 3:10 AM
    Edited by: Muhammad on Feb 28, 2010 3:21 AM

  • How to update items in combo box programmat​ically

    I have a problem on updating items in combo box programmatically, such as add or remove a item from the list. I can add or delete without any problem once the vi is running. I can see it is changed by pressing drop button. But after I close the vi and rerun it, the change I did last time is lost. It seems it not permenatly change the list. Anyone has an idea?

    If you are changing the list programmatically why do you believe that it should be permanent? If it's permanent, why are you changing it programmatically? Doesn't make a whole lot of sense.
    If you're talking about saving the values as "default" in the same way you do with the development environment, you cannot do this with an EXE. This is a FAQ. You have to update the list programmatically, saving the "new" default values to file.

  • Strange behaviour with my updating of combo box

    public class EditVideoDialog extends JPanel implements ActionListener{
         JTextField text_Name, text_Price, text_Producer, path_Picture;
         JTextArea textarea_Description;
         public JComboBox combo_Genre, combo_Name;
         String old_VideoName;
         Vector <String> myVideoName = new Vector <String>();
         public EditVideoDialog(){
         public EditVideoDialog(Vector <String> myVideoName){          
              combo_Name = new JComboBox();
              combo_Name.setEditable(false);
              combo_Name.setMaximumRowCount(4);
              combo_Name.setPreferredSize(new Dimension(300,25));
              currentVideoName(myVideoName);
         //Function to set current video name
         public void currentVideoName(Vector <String>videoName){
              combo_Name.removeAllItems();
              combo_Name.addItem("");
              for(int k =0; k<videoName.size(); k++){
                   combo_Name.addItem(videoName.get(k));
    }I tried with the script above, the combo_box first got compiled nicely after retrieving data from the database.
    However, when i tried to do the updating of combo box with function currentVideoName, it fails.
    I also tried puttng a ComboBoxModel inside my function but it fails. It just doesn't get updated...
    ComboBoxModel model = new DefaultComboBoxModel(myVideoName);
    combo_Name.setModel(model);can someone advise me or show me some simple code on this?
    Edited by: diskhub on Mar 16, 2008 11:27 AM

    http://forum.java.sun.com/thread.jspa?threadID=5275345

  • 2 combo box on a single jtable cell

    I need to add two combo box to a single jtable cell..One for selecting the number and the other for specifying whether the number specifies daily, weekly or yearly data .Please help

    hey thank you so much....it worked..... i am adding the code .....
    this is how you add an editor to a column
               TableColumn col=jtInfo.getColumnModel().getColumn(2);
               col.setCellEditor(new ComboCellEditor());the class that extends cell editor
        public class ComboCellEditor extends JPanel implements TableCellEditor
            public Component getTableCellEditorComponent(JTable table,Object value, boolean isSelected,int row, int column)
               this.setLayout(new GridLayout(1,2));
               if(column==2)
                     jcbCombo1=new JComboBox();
                     for(int i=1;i<31;i++)
                       jcbCombo1.addItem(i);
                     jcbCombo2=new JComboBox();
                     jcbCombo2.addItem("Days");
                     jcbCombo2.addItem("Weeks");
                     jcbCombo2.addItem("Months");
                     this.add(jcbCombo1);
                     this.add(jcbCombo2);
                return this;
            public Object getCellEditorValue()
                return this;
            public boolean isCellEditable(EventObject e)
                return true;
            public boolean shouldSelectCell(EventObject e)
                return true;
            public boolean stopCellEditing()
                return false;
            public void cancelCellEditing()
            public void addCellEditorListener(CellEditorListener e)
            public void removeCellEditorListener(CellEditorListener e)
        }

Maybe you are looking for