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)
    }

Similar Messages

  • Turn a single jtable cell into 2 swing component

    Hi, i'm trying to turn a jtable cell into two components, a jlabel and a jtextarea with the label on top of the textarea. Is that possible?
    I can write my own renderer and editor and turn a cell into a combobox or textarea. But is it possible to put two renderers in a single cell?
    thanks

    A JPanel IS-A Component so you could follow the procedure outlined in Sun's Tutorial and create a JPanel subclass that implements TableCellRenderer. For an editor the tutorial recommends subclassing AbstractCellEditor and implementing getTableCellEditorComponent() to return the panel containing your stuff.
    I haven't done this, but it seems worth a try. If you get stuck the best (most knowledgable, quickest) help is to be had from the [Swing forum|http://forum.java.sun.com/forum.jspa?forumID=57].
    Edited by: pbrockway2 on Jul 10, 2008 12:04 PM

  • JTable Cell with two icons

    Hello -
    I'm rather new to Java, so please excuse me if this is a simple question. For a project I am working on, I am attempting to deal with placing two icons in a single JTable cell. For the life of me I have no idea if this is even feasible, let alone how I would implement it. Originally I thought about attempting to overload the JLabel class (as this is what the JTable cell is based upon, if I'm not mistaken?) and allowing two icons to be placed per label.
    Am I on the right track? Is this even possible? Any suggestions?
    Thanks much.

    Please read the forum for JTable.
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    You will know that you canuse any component as CellRenderer, this component can have whatever you want (say 2 icons and 5 comboboxes)
    here is short example that shows 2 icons in JTable
    import java.awt.*;
    import java.awt.image.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TwoIcons extends JFrame {
         public static void main(String[] args){
              createIcons();
              SwingUtilities.invokeLater
                   new Runnable()
                        public void run() {
                             new TwoIcons();
         public TwoIcons(){
              super("Test");
              DefaultTableModel tm = new DefaultTableModel(
                   new Object[][]{
                        {new IconPair("cross", "cross"), "just a string"},
                        {new IconPair("circle", "cross"),"just another string"},
                        {new IconPair("String", "circle"),"yet another string"}
                   }, new String[]{"Two Icons","String"}){
                   public Class getColumnClass(int columnIndex){
                        if(columnIndex==0){
                             return IconPair.class;
                        else
                             return super.getColumnClass(columnIndex);
              JTable table = new JTable(tm);
              final Color bg = table.getBackground();
              table.setDefaultRenderer(IconPair.class, new TableCellRenderer(){
                        RendererPanel renderer = new RendererPanel(bg);
                        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                             renderer.setIcons((IconPair)value);
                             return  renderer;
              JScrollPane scp = new JScrollPane(table);
              add(scp);
              setSize(400,100);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              pack();
              setVisible(true);
         class RendererPanel extends JPanel{
              JLabel tf1,tf2;
              RendererPanel(Color bg){
                   setLayout(new BoxLayout(this,BoxLayout.LINE_AXIS) );
                   tf1=new JLabel();
                   tf2=new JLabel();
                   add(tf1);
                   add(Box.createRigidArea(new Dimension(5,0)));
                   add(tf2);
                   setBackground(bg);
              public void setIcons(IconPair value) {
                   tf1.setIcon(value.i1);
                   tf2.setIcon(value.i2);
                   //uncomment next 2 lines if you want text as well
    //               tf1.setText(value.s1);
    //               tf2.setText(value.s2);
         class IconPair {
              public Icon i1,i2;
              public String s1,s2;
              IconPair(String s1, String s2){
                   this.i1=icons.get(s1);
                   this.i2=icons.get(s2);
                   this.s1=s1;
                   this.s2=s2;
         static Map<String,Icon> icons = new HashMap<String,Icon>();
         public static  void createIcons(){
              Image img = new BufferedImage(10,10, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g2=(Graphics2D)(img.getGraphics());
              g2.setColor(Color.RED);
              g2.drawLine(0,0,10,10);
              g2.drawLine(0,10,10,0);
              icons.put("cross",new ImageIcon(img));
              img = new BufferedImage(10,10, BufferedImage.TYPE_INT_ARGB);
              g2=(Graphics2D)(img.getGraphics());
              g2.setColor(Color.GREEN);
              g2.drawOval(1,1,8,8);
              icons.put("circle",new ImageIcon(img));
    }

  • Rendering multiple objects in JTable cells

    Hi,
    I wish to render in a single JTable cell (actually all cells in a Column) an ImageIcon and it's associated description string. The description string should be rendered below the ImageIcon, as it's caption. How can this be done? I assume a custom cell renderer, but the details are muddy at this point.
    thanks!
    JPL

    Thanks.
    I have looked atthe tutorial, but it focuses on a single object type per cell - I've got two different types (an ImageIcon and a String) that will occupuy a single cell.
    Taking a conceptual leap here, is it possible to create a new TableCellRenderer that houses a JPanel and GridLayout, and then place an ImageIcon and JLabel into that panel? I guess as long as things are JComponents, should I be OK with this approach?
    thanks,
    jpl

  • Push Button , Label and combo box

    Hi Experts,
    Currently facing a problem , please guide.
    I have two push buttons say A and B and one combo box.
    I am using Combo box with source data as filtered row options.
    What I want to accomplish is when push button A is clicked then my combo box should have different souce of data say sheet 1 in excel and when Push button B is clicked then the same combo box should have source data from sheet 2 from the same excel.
    I mean dynamic selection of source data and then destination data by using combo boxed.
    is it possible ?
    Thanks in advance.
    Thanks & Regards,
    Anjna

    Hi,
    Use 2 combo boxs CB1 n CB 2.
    CB1 : source form sheet1
    CB2:Source from sheet 2
    when push button  A is selected  set dynamic visibility such that u get combo box 1
    when push button  B is selected  set dynamic visibility such that u get combo box 2.
    Case 2:
    Insted of using 2 push buttons you can use a radio butoon and select the lables A or B so that these two combo box components dnt appear at once
    Take a radio button component and map lables as A and B
    under behaviour tab: >Insert selected item:>mapp it with a blank cell say Sheet3!$G$4
    if radio button selection is A then set dynamic visibility such that u get combo box 1
    if radio button selection is b then set dynamic visibility such that u get combo box 2
    formula cells:
    take a blak cell say Sheet3!$H$7 and write formula =IF(Sheet3!$G$4="A","",first label of combo box 2)
    take a blak cell say Sheet3!$H$8 and write formula =IF(Sheet3!$G$4="B","",first label of combo box 1)
    Combo box 1 :Behaviour tab-->Selected item :Sheet3!$H$7
    Combo box 1 :Behaviour tab-->Selected item :Sheet3!$H$8
    check if this suits ur req ...
    @Sri
    Edited by: Sri kamesh on Jun 21, 2011 11:00 AM

  • Code to change JTable cell color not working

    My code below is supposed to change the color
    of a single JTable cell however its not working.
    Could anyone please tell me why?
    Here's the code:
    import java.awt.*;
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ColorTable extends JTable {
    public ColorTable() {
    AbstractTableModel tableModel = new AbstractTableModel() {
    public Class getColumnClass(int column) { return Integer.class; }
    public int getColumnCount() { return 6; }
    public int getRowCount() { return 10;}
    public Object getValueAt(int row,int col) { return new Integer(row * col); }
    setModel(tableModel);
    setDefaultRenderer(Integer.class,new ColorRenderer(Color.cyan));
    this.setRowSelectionAllowed(false);
    this.setCellSelectionEnabled(true);
    addMouseListener(new MouseAdapter() {
    private ColorRenderer renderer;
    private JColorChooser chooser = new JColorChooser();
    public void mousePressed(MouseEvent e) {
    if(e.getModifiers() == MouseEvent.BUTTON3_MASK) {
    System.out.print("rowAtPoint(e.getPoint())=" +rowAtPoint(e.getPoint()));
    System.out.print( "columnAtPoint(e.getPoint()))=" + columnAtPoint(e.getPoint()));
    renderer = (ColorRenderer)getCellRenderer(rowAtPoint(e.getPoint()), columnAtPoint(e.getPoint()));
    // chooser.setColor(renderer.getColor());
    renderer.setColor(chooser.showDialog((Component)e.getSource(),"Choose Cell Color",chooser.getColor()));
    class ColorRenderer extends DefaultTableCellRenderer {
    private Color cellColor;
    public ColorRenderer(Color color) { cellColor = color; }
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    System.out.print("row= " + row + "\n");
    System.out.print("column= " + column + "\n");
    System.out.print("OBJECT VALUE=" + value.toString());
    //Component comp = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    if (isSelected) {
    setOpaque(true);
    setBackground(cellColor);
    else {
    setBackground(Color.white);
    setForeground(Color.black);
    return this;
    public void setColor(Color color)
    cellColor = color;
    ColorTable.this.repaint();
    public Color getColor() { return cellColor; }
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    ColorTable table = new ColorTable();
    panel.add(table);
    frame.getContentPane().add(panel);
    frame.setSize(500,250);
    frame.setVisible(true);

    My code below is supposed to change the color
    of a single JTable cell however its not working.
    Could anyone please tell me why?
    Here's the code:
    import java.awt.*;
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ColorTable extends JTable {
    public ColorTable() {
    AbstractTableModel tableModel = new AbstractTableModel() {
    public Class getColumnClass(int column) { return Integer.class; }
    public int getColumnCount() { return 6; }
    public int getRowCount() { return 10;}
    public Object getValueAt(int row,int col) { return new Integer(row * col); }
    setModel(tableModel);
    setDefaultRenderer(Integer.class,new ColorRenderer(Color.cyan));
    this.setRowSelectionAllowed(false);
    this.setCellSelectionEnabled(true);
    addMouseListener(new MouseAdapter() {
    private ColorRenderer renderer;
    private JColorChooser chooser = new JColorChooser();
    public void mousePressed(MouseEvent e) {
    if(e.getModifiers() == MouseEvent.BUTTON3_MASK) {
    System.out.print("rowAtPoint(e.getPoint())=" +rowAtPoint(e.getPoint()));
    System.out.print( "columnAtPoint(e.getPoint()))=" + columnAtPoint(e.getPoint()));
    renderer = (ColorRenderer)getCellRenderer(rowAtPoint(e.getPoint()), columnAtPoint(e.getPoint()));
    // chooser.setColor(renderer.getColor());
    renderer.setColor(chooser.showDialog((Component)e.getSource(),"Choose Cell Color",chooser.getColor()));
    class ColorRenderer extends DefaultTableCellRenderer {
    private Color cellColor;
    public ColorRenderer(Color color) { cellColor = color; }
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    System.out.print("row= " + row + "\n");
    System.out.print("column= " + column + "\n");
    System.out.print("OBJECT VALUE=" + value.toString());
    //Component comp = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    if (isSelected) {
    setOpaque(true);
    setBackground(cellColor);
    else {
    setBackground(Color.white);
    setForeground(Color.black);
    return this;
    public void setColor(Color color)
    cellColor = color;
    ColorTable.this.repaint();
    public Color getColor() { return cellColor; }
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    ColorTable table = new ColorTable();
    panel.add(table);
    frame.getContentPane().add(panel);
    frame.setSize(500,250);
    frame.setVisible(true);

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

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

  • Single JTable Column with several diff Cell Editors

    Am trying to create a single JTable column that can have several different cell editors. Java seems to be bias to having 1 cell editor for the whole column.
    For example in 1 column can I have
    Row1 : TextBox
    Row2: Check Box
    Row3: Radio Buttons
    Row4: JColorChooser
    At the moment I can only have one CellEditor for the whole column which is not very helpful.

    the default implementation offers to provide editors per column in the tableColumn and/or editors per class type by setting default editors ( JTable.setDefaultEditor(Class class, TableCellEditor editor) ). If you look at the getCellEditor method of JTable you see that first the tablecolumns are asked for an editor, and if this doesnt succeed a default editor for the class acording to the value at the passed grid position is determined.
    If this does not fullfil your needs, you can still overwrite the getCellEditor method of JTable and return whatever editor is suitable.
    regards,
    stefan

  • 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

  • Combo in JTable Cell

    Hi Everyone,
    1) I want to display combo boxes in some selected colmns of my JTable.
    2) I want the user to enter table cell's edit mode directly when he clicks on a cell.
    For above functionality No. 2), i got following running code from this forum (Mr. Camickr) as follows. Can you guys suggest me where and how to add code to display combo?
    Thanks in advance.
    Girish Varde
    ** For text selection you have two choices. Remove the "xxx" from either
    ** editCellAt() or prepareEditor() method.
    ** The difference is in how mouse double clicking works
    ** To place a cell directly into edit mode, use the changeSelection() method.
    ** Be aware this will generate a TableModelEvent every time you leave a cell.
    ** You can also use either of the above text selection methods.

    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.table.*;

    public class TableEditCell extends JFrame
    public TableEditCell()
    String[] columnNames = {"Number", "Letter"};
    Object[][] data = { {"1", "A"}, {"2", "B"}, {"3", "C"} };

    JTable table = new JTable(data, columnNames)
    // Place cell in edit mode when it 'gains focus'

    public void xxxchangeSelection(
    int row, int column, boolean toggle, boolean extend)
    super.changeSelection(row, column, toggle, extend);

    if (editCellAt(row, column))
    getEditorComponent().requestFocusInWindow();

    // Select the text when the cell starts editing
    // a) text will be replaced when you start typing in a cell
    // b) text will be selected when you use F2 to start editing
    // c) text will be selected when double clicking to start editing

    public boolean xxxeditCellAt(int row, int column, EventObject e)
    boolean result = super.editCellAt(row, column, e);
    final Component editor = getEditorComponent();

    if (editor != null && editor instanceof JTextComponent)
    if (e == null)
    ((JTextComponent)editor).selectAll();
    else
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    ((JTextComponent)editor).selectAll();

    return result;

    // Select the text when the cell starts editing
    // a) text will be replaced when you start typing in a cell
    // b) text will be selected when you use F2 to start editing
    // c) caret is placed at end of text when double clicking to start editing

    public Component xxxprepareEditor(
    TableCellEditor editor, int row, int column)
    Component c = super.prepareEditor(editor, row, column);

    if (c instanceof JTextComponent)
    ((JTextField)c).selectAll();

    return c;

    JScrollPane scrollPane = new JScrollPane( table );
    getContentPane().add( scrollPane );

    public static void main(String[] args)
    TableEditCell frame = new TableEditCell();
    frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
    frame.pack();
    frame.setLocationRelativeTo( null );
    frame.setVisible(true);
    -------------------------------------------------------------------------------------------------------�

    OK. Here is my code divided in two classes
    package com.apsiva.client.pi;
    * @author Administrator
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    import com.apsiva.client.iedit.ItemCellEditor;
    public class TableEditCell extends JFrame
            public TableEditCell()
                    String[] columnNames = {"Number", "Letter"};
                    Object[][] data = { {"1", "A"}, {"2", "B"}, {"3", "C"} };
                    JTable table = new JTable(data, columnNames)
                            //  Place cell in edit mode when it 'gains focus'
                            public void changeSelection(
                                    int row, int column, boolean toggle, boolean extend)
                                    super.changeSelection(row, column, toggle, extend);
                                    if (editCellAt(row, column))
                                            getEditorComponent().requestFocusInWindow();
                            //  Select the text when the cell starts editing
                            //  a) text will be replaced when you start typing in a cell
                            //  b) text will be selected when you use F2 to start editing
                            //  c) text will be selected when double clicking to start editing
    //                        public boolean xxxeditCellAt(int row, int column, EventObject e)
                            public boolean xxxeditCellAt(int row, int column, EventObject e)
                                    boolean result = super.editCellAt(row, column, e);
                                    final Component editor = getEditorComponent();
                                    if (editor != null && editor instanceof JTextComponent)
                                            if (e == null)
                                                    ((JTextComponent)editor).selectAll();
                                            else
                                                    SwingUtilities.invokeLater(new Runnable()
                                                            public void run()
                                                                    ((JTextComponent)editor).selectAll();
                                    return result;
                            //  Select the text when the cell starts editing
                            //  a) text will be replaced when you start typing in a cell
                            //  b) text will be selected when you use F2 to start editing
                            //  c) caret is placed at end of text when double clicking to start editing
    //                        public Component xxxprepareEditor(
                            public Component prepareEditor(
                                    TableCellEditor editor, int row, int column)
                                    Component c = super.prepareEditor(editor, row, column);
                                    if (c instanceof JTextComponent)
                                            ((JTextField)c).selectAll();
                                    return c;
                    JScrollPane scrollPane = new JScrollPane( table );
                    getContentPane().add( scrollPane );
                    String[] data1 = {"A","B","C"} ;
                    String[] data2 = {"D","E","F"} ;
                    String[] data3 = {"G","H","I"} ;
                    Vector comboBoxModels = new Vector() ;
                    comboBoxModels.addElement(new DefaultComboBoxModel(data1)) ;
                    comboBoxModels.addElement(new DefaultComboBoxModel(data2)) ;
                    comboBoxModels.addElement(new DefaultComboBoxModel(data3)) ; 
                    ItemCellEditor ice = new ItemCellEditor(new JComboBox(comboBoxModels));
                    table.getColumnModel().getColumn(0).setCellEditor(ice) ;
            public static void main(String[] args)
                    TableEditCell frame = new TableEditCell();
                    frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
                    frame.pack();
                    frame.setLocationRelativeTo( null );
                    frame.setVisible(true);
    package com.apsiva.client.iedit;
    * @author Administrator
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    * Created on Mar 16, 2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    import java.awt.Component;
    import java.util.EventObject;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.event.CellEditorListener;
    * @author Administrator
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    public class ItemCellEditor extends  DefaultCellEditor implements javax.swing.table.TableCellEditor {
          * @param arg0
         public ItemCellEditor(JComboBox arg0) {
              super(arg0);
              // TODO Auto-generated constructor stub
         /* (non-Javadoc)
          * @see javax.swing.CellEditor#addCellEditorListener(javax.swing.event.CellEditorListener)
         /* (non-Javadoc)
          * @see javax.swing.table.TableCellEditor#getTableCellEditorComponent(javax.swing.JTable, java.lang.Object, boolean, int, int)
          public Component getTableCellEditorComponent(
                     JTable table, Object value, boolean isSelected,int row,
                     int column ) {
              // TODO Auto-generated method stub
    //                      if (iRowToEdit != row)  //For disabling editing
    //                      return null;
                          int i = 0;
    //                      return super.getTableCellEditorComponent(
    //                      table, value, isSelected,row, column );
                          JComboBox combo = (JComboBox) super.getTableCellEditorComponent(
                                    table, value, isSelected,row, column );
                         String[] data1 = {"A","B","C"} ;
                         String[] data2 = {"D","E","F"} ;
                         String[] data3 = {"G","H","I"} ;
                         Vector comboOptions = new Vector();
                         comboOptions.add("Choice 1");
                           comboOptions.add("Choice 2");
                            comboOptions.add("Choice 3");
                            comboOptions.add("Choice 4");
                         ComboBoxModel comboBoxModels = new DefaultComboBoxModel(comboOptions) ;
                         combo.setModel(comboBoxModels);
                      if (column == 0 )   return combo;
                          return super.getTableCellEditorComponent(
                                    table, value, isSelected,row, column );
         /* (non-Javadoc)
          * @see javax.swing.CellEditor#addCellEditorListener(javax.swing.event.CellEditorListener)
         public void addCellEditorListener(CellEditorListener arg0) {
              // TODO Auto-generated method stub
               int i = 0;
         /* (non-Javadoc)
          * @see javax.swing.CellEditor#cancelCellEditing()
         public void cancelCellEditing() {
              // TODO Auto-generated method stub
               int i = 0;
         /* (non-Javadoc)
          * @see javax.swing.CellEditor#getCellEditorValue()
         public Object getCellEditorValue() {
              // TODO Auto-generated method stub
               int i = 0;
              return null;
         /* (non-Javadoc)
          * @see javax.swing.CellEditor#isCellEditable(java.util.EventObject)
         public boolean isCellEditable(EventObject arg0) {
              // TODO Auto-generated method stub
              JTable table = (JTable)arg0.getSource();
              int column = table.getSelectedColumn();
               int i = 0;
               return true;
         /* (non-Javadoc)
          * @see javax.swing.CellEditor#removeCellEditorListener(javax.swing.event.CellEditorListener)
         public void removeCellEditorListener(CellEditorListener arg0) {
               int i = 0;
              // TODO Auto-generated method stub
         /* (non-Javadoc)
          * @see javax.swing.CellEditor#shouldSelectCell(java.util.EventObject)
         public boolean shouldSelectCell(EventObject arg0) {
              // TODO Auto-generated method stub
               int i = 0;
              return true;
         /* (non-Javadoc)
          * @see javax.swing.CellEditor#stopCellEditing()
         public boolean stopCellEditing() {
              // TODO Auto-generated method stub
               int i = 0;
              return false;
    --------------------------------------------------------------------------------------------------When i click outside table, then once again the cells become editable unless first column is clicked.
    Please suggest a solution.
    Thanks and regards,
    Girish Varde

  • 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.

Maybe you are looking for

  • Which Oracle XE dialect?

    Please, could help me? I am a new user Oracle, could help me, please? Which dialect for Oracle XE could usage in the Hibernate? I already used OracleDialect and Oracle9Dialect, but it didn't function. Certain of your understanding, at once I thank. U

  • My store setting does not have a sign out

    In the setting - store - I cannot see a sign out bar only to sign in.

  • Im trying to update my iphone but it says must connect to wifi

    Im cconnected to  the internet and trying to update the software on my iphone but it says it needs wifi connection - but Im connected??

  • Use of xmltable

    Hi, I have the follwing xml in column tmp_xml of table tmp_table: <env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">    <env:Header/>    <env:Body>       <ses:getCriteriaNamesListResponse xmlns:ses="http://session.kernel.cmp.com/">

  • Where is the instruction manual for the Ipod Nano??

    I just got my Ipod Nano and all I got was a small fold out booklet with NO instructions on acutally adding songs to my ipod. Where can I get one?? I need to know how to put songs on it from my computer and just how to use the dang thing.