Problem in jtable cell

Hi
I am facing one problem. there is some data should be displayed in Jtable cell.
The thing is that the whole data shall be visible in the cell.. for this I am writing one renderer.. but I could not find the desire solution.. please check it out
class Item_Details extends JFrame {
    ApsJTable itemTable = null;
     ApsJTable imageTable = null;     
     ArrayList data = new ArrayList();
     String[] columns = new String[2];
     ArrayList data1 = new ArrayList();
     String[] columns1 = new String[2];
     ItemTableModel itemTableModel = null;
     ItemTableModel itemTableModel1 = null;
     public Item_Details()
          super("Item Details");          
         this.setSize(600,100);
          this.setVisible(true);
         init();          
     private void init(){
          ////////////// Get data for first Table Model  ////////////////////////////
          data = getRowData();
          columns = getColData();
          System.out.println(columns[0]);
         itemTableModel = new ItemTableModel(data,columns);
         /////////////Get Data for Second Table Model //////////////////////////////
          try{
                    data1 = getRowData1();
             }catch(Exception e){}
          columns1 = getColumns1();
         itemTableModel1 = new ItemTableModel(data1,columns1);
         ///////////// Set Data In Both Table Model //////////////////////////////////
          itemTable = new ApsJTable(itemTableModel);
          imageTable = new ApsJTable(itemTableModel1);
          this.itemTable.setShowGrid(false);
          this.imageTable.setShowGrid(false);
          this.itemTable.setColumnSelectionAllowed(false);
          this.imageTable.setColumnSelectionAllowed(false);
          System.out.println(itemTable.getColumnCount());
          this.imageTable.setRowHeight(getImageHeight()+3);
          JScrollPane tableScrollPane = new JScrollPane(this.imageTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
          tableScrollPane.setRowHeaderView(this.itemTable);
          tableScrollPane.getRowHeader().setPreferredSize(new Dimension(800, 0));
          itemTable.getTableHeader().setReorderingAllowed(false);
          itemTable.setColumnSelectionAllowed(false);
          //itemTable.setRowHeight(25);
          itemTable.setCellSelectionEnabled(false);
          itemTable.setFocusable(false);
          imageTable.getTableHeader().setReorderingAllowed(false);
          imageTable.setFocusable(false);
          imageTable.setCellSelectionEnabled(false);
          //tableScrollPane.setOpaque(false);
          itemTable.setAutoCreateColumnsFromModel(false);
          int columnCount = itemTable.getColumnCount();
          for(int k=0;k<columnCount;k++)
          /*     TableCellRenderer renderer = null;
               TableCellEditor editor = null;
               renderer = new TextAreaCellRenderer();     // NEW
               editor = new TextAreaCellEditor();     
               TableColumn column = new TableColumn(k,itemTable.getColumnModel().getColumn(k).getWidth(),renderer, editor);
                    itemTable.addColumn(column);*/
               itemTable.getColumnModel().getColumn(k).setCellRenderer(new MultiLineCellRenderer());
               //itemTable.getColumnModel().getColumn(k).setCellEditor(new TextAreaCellEditor());
////////////---------------------- Here background color is being set--------------//////////////////
          this.imageTable.getParent().setBackground(Color.WHITE);
          this.itemTable.getParent().setBackground(Color.WHITE);
          tableScrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER,this.itemTable.getTableHeader());
          getContentPane().add(tableScrollPane,BorderLayout.CENTER);
          getContentPane().setVisible(true);
     public static void main(String[] str){
          com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode", "2005/05/28#[email protected]#1v2pej6#1986ew");
          try {
            javax.swing.LookAndFeel alloyLnF = new com.incors.plaf.alloy.AlloyLookAndFeel();
            javax.swing.UIManager.setLookAndFeel(alloyLnF);
          } catch (javax.swing.UnsupportedLookAndFeelException ex) {
          ex.printStackTrace();
          Item_Details ID = new Item_Details();
          ID.setVisible(true);
public ArrayList getRowData()
     ArrayList rowData=new ArrayList();
     Hashtable item = new Hashtable();
     item.put(new Long(0),new String("Item No:"));
     item.put(new Long(1),new String("RED-1050"));
     rowData.add(0,item);
     item = new Hashtable();
     item.put(new Long(0),new String("Description:"));
     item.put(new Long(1),new String("SYSTEM 18 mbh COOLING 13 mbh HEATING 230/208 v POWER AIRE "));
     rowData.add(1,item);
     item = new Hashtable();
     item.put(new Long(0),new String("Stage:"));
     item.put(new Long(1),new String("Draft"));
     rowData.add(2,item);
     item = new Hashtable();
     item.put(new Long(0),new String("Price: "));
     item.put(new Long(1),new String(" 999.00"));
     rowData.add(3,item);
     item = new Hashtable();
     item.put(new Long(0),new String("Features:"));
     item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
     rowData.add(4,item);
     /*item.put(new Long(0),new String("Family Sequence"));
     item.put(new Long(1),new String("8.00"));
     rowData.add(5,item);
     item.put(new Long(0),new String("Family Sequence"));
     item.put(new Long(1),new String("8.00"));
     rowData.add(6,item);
     item.put(new Long(0),new String("Family Sequence"));
     item.put(new Long(1),new String("8.00"));
     rowData.add(7,item);
     return rowData;
public String[] getColData()
     String[] colData = new String[]{"Attribute","Value"};
     return colData;
public ArrayList getRowData1()throws MalformedURLException{
     ArrayList rowData = new ArrayList();
     Hashtable item = new Hashtable();
     String str = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
     URL url = new URL(str);
     ImageIcon ic = new ImageIcon(url);
     ImageIcon scaledImage = new ImageIcon(ic.getImage().getScaledInstance(getImageHeight(), -1,Image.SCALE_SMOOTH));
     item.put(new Long(0), scaledImage);
     rowData.add(0,item);
     String str1 = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
     URL url1 = new URL(str1);
     ImageIcon ic1 = new ImageIcon(url1);
     ImageIcon scaledImage1 = new ImageIcon(ic1.getImage().getScaledInstance(120, -1,Image.SCALE_DEFAULT));
     item.put(new Long(0),scaledImage1);
     rowData.add(1,item);
     return rowData;
public String[] getColumns1(){
     String[] colData = new String[]{"Image"}; 
     return colData;
public int getImageHeight(){
     ImageIcon ic = new ImageIcon("c:\\image\\ImageNotFound.gif");
     return ic.getIconHeight();
class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
       public MultiLineCellRenderer() {
            setLineWrap(true);
            setWrapStyleWord(true);
         JScrollPane m_scroll = new JScrollPane(this,
                   JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                   JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
         setOpaque(true);
       public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
            /*if (isSelected) {
           setForeground(table.getSelectionForeground());
           setBackground(table.getSelectionBackground());
         } else {
           setForeground(table.getForeground());
           setBackground(table.getBackground());
        // setFont(table.getFont());
        /* if (hasFocus) {
           setBorder( UIManager.getBorder("Table.focusCellHighlightBorder") );
           if (table.isCellEditable(row, column)) {
             setForeground( UIManager.getColor("Table.focusCellForeground") );
             setBackground( UIManager.getColor("Table.focusCellBackground") );
         } else {
           setBorder(new EmptyBorder(1, 2, 1, 2));
         int width = table.getColumnModel().getColumn(column).getWidth();
          //setSize(width, 1000);
          int rowHeight = getPreferredSize().height;
          if (table.getRowHeight(row) != rowHeight)
               table.setRowHeight(row, rowHeight);
         setText((value == null) ? "" : value.toString());
         return this;
     }what wrong with this code..
Thanks

In summary, you have one or more columns for which the data must be wholly visible - correct? If you need all the columns to show the whole of their data, you are goinf to have to expand the table, otherwise you can expand a column with something like
myTable.getColumnModel().getColumn(whichever).setPreferredWidth(whatever);

Similar Messages

  • Problem in JTable cell renderer

    Hi
    One problem in JTable cell. Actually I am using two tables while I am writing renderer for word raping in first table .. but it is affected in last column only remain is not being effected�. Please chaek it out what is exact I am missing�
    Thanks
    package com.apsiva.tryrowmerge;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.EventObject;
    import java.util.Hashtable;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.border.Border;
    import javax.swing.border.EmptyBorder;
    import javax.swing.event.*;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    class Item_Details extends JFrame {
        ApsJTable itemTable = null;
         ApsJTable imageTable = null;     
         ArrayList data = new ArrayList();
         String[] columns = new String[2];
         ArrayList data1 = new ArrayList();
         String[] columns1 = new String[2];
         ItemTableModel itemTableModel = null;
         ItemTableModel itemTableModel1 = null;
         public Item_Details()
              super("Item Details");          
             this.setSize(600,100);
             this.setBackground(Color.WHITE);
              this.setVisible(true);
             init();          
         private void init(){
              ////////////// Get data for first Table Model  ////////////////////////////
              data = getRowData();
              columns = getColData();
              System.out.println(columns[0]);
             itemTableModel = new ItemTableModel(data,columns);
             /////////////Get Data for Second Table Model //////////////////////////////
              try{
                        data1 = getRowData1();
                 }catch(Exception e){}
              columns1 = getColumns1();
             itemTableModel1 = new ItemTableModel(data1,columns1);
             ///////////// Set Data In Both Table Model //////////////////////////////////
              itemTable = new ApsJTable(itemTableModel);
              imageTable = new ApsJTable(itemTableModel1);
              this.itemTable.setShowGrid(false);
              this.imageTable.setShowGrid(false);
              this.itemTable.setColumnSelectionAllowed(false);
              this.imageTable.setColumnSelectionAllowed(false);
              System.out.println(itemTable.getColumnCount());
              this.imageTable.setRowHeight(getImageHeight()+3);
              JScrollPane tableScrollPane = new JScrollPane(this.imageTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              tableScrollPane.setRowHeaderView(this.itemTable);
              //itemTable.getColumnModel().getColumn(0).setMaxWidth(200);
              itemTable.getColumnModel().getColumn(0).setPreferredWidth(200);
              itemTable.getColumnModel().getColumn(1).setPreferredWidth(600);
              tableScrollPane.getRowHeader().setPreferredSize(new Dimension(800, 0));
              itemTable.getTableHeader().setResizingAllowed(false);
              itemTable.getTableHeader().setReorderingAllowed(false);
              itemTable.setColumnSelectionAllowed(false);
              //itemTable.setRowHeight(25);
              itemTable.setCellSelectionEnabled(false);
              itemTable.setFocusable(false);
              imageTable.getTableHeader().setReorderingAllowed(false);
              imageTable.setFocusable(false);
              imageTable.setCellSelectionEnabled(false);
              //tableScrollPane.setOpaque(false);
              itemTable.setAutoCreateColumnsFromModel(false);
              int columnCount = itemTable.getColumnCount();
              for(int k=0;k<columnCount;k++)
                   TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();     // NEW
              //     editor = new TextAreaCellEditor();     
              //     TableColumn column = new TableColumn(k,itemTable.getColumnModel().getColumn(k).getWidth(),renderer, editor);
                   System.out.println(k);
                   itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);          
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(editor);
                   /*itemTable.getColumnModel().getColumn(1).setCellRenderer(new TextAreaCellRenderer());
                   itemTable.getColumnModel().getColumn(1).setCellEditor(new TextAreaCellEditor());*/
    //               itemTable.setShowGrid(false);
                   //itemTable.addColumn(column);
                   //itemTable.getColumnModel().getColumn(k).setCellRenderer(new MultiLineCellRenderer());
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(new TextAreaCellEditor());
    ////////////---------------------- Here background color is being set--------------//////////////////
              this.imageTable.getParent().setBackground(Color.WHITE);
              this.itemTable.getParent().setBackground(Color.WHITE);
              tableScrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER,this.itemTable.getTableHeader());
              getContentPane().add(tableScrollPane,BorderLayout.CENTER);
              getContentPane().setVisible(true);
         public static void main(String[] str){
              com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode", "2005/05/28#[email protected]#1v2pej6#1986ew");
              try {
                javax.swing.LookAndFeel alloyLnF = new com.incors.plaf.alloy.AlloyLookAndFeel();
                javax.swing.UIManager.setLookAndFeel(alloyLnF);
              } catch (javax.swing.UnsupportedLookAndFeelException ex) {
              ex.printStackTrace();
              Item_Details ID = new Item_Details();
              ID.setVisible(true);
    public ArrayList getRowData()
         ArrayList rowData=new ArrayList();
         Hashtable item = new Hashtable();
         item.put(new Long(0),new String("Item No:aaaaaaa aaaaaaaa aaaaaaaaa aaaaaa"));
         item.put(new Long(1),new String("RED-1050"));
         rowData.add(0,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Description:rt r trtrt rttrytrr tytry trytry tr tr rty thyjyhjhnhnhgg hhjhgjh"));
         item.put(new Long(1),new String("SYSTEM 18 mbh COOLING 13 mbh HEATING 230/208 v POWER AIRE "));
         rowData.add(1,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Stage:"));
         item.put(new Long(1),new String("Draft"));
         rowData.add(2,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Price: "));
         item.put(new Long(1),new String("999.00"));
         rowData.add(3,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(4,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(5,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(6,item);
         /*item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(5,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(6,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(7,item);
         return rowData;
    public String[] getColData()
         String[] colData = new String[]{"Attribute","Value"};
         return colData;
    public ArrayList getRowData1()throws MalformedURLException{
         ArrayList rowData = new ArrayList();
         Hashtable item = new Hashtable();
         String str = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url = new URL(str);
         ImageIcon ic = new ImageIcon(url);
         ImageIcon scaledImage = new ImageIcon(ic.getImage().getScaledInstance(getImageHeight(), -1,Image.SCALE_SMOOTH));
         item.put(new Long(0), scaledImage);
         rowData.add(0,item);
         String str1 = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url1 = new URL(str1);
         ImageIcon ic1 = new ImageIcon(url1);
         ImageIcon scaledImage1 = new ImageIcon(ic1.getImage().getScaledInstance(120, -1,Image.SCALE_DEFAULT));
         item.put(new Long(0),scaledImage1);
         rowData.add(1,item);
         return rowData;
    public String[] getColumns1(){
         String[] colData = new String[]{"Image"}; 
         return colData;
    public int getImageHeight(){
         ImageIcon ic = new ImageIcon("c:\\image\\ImageNotFound.gif");
         return ic.getIconHeight();
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
         public TextAreaCellRenderer() {
              setEditable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
         public Component getTableCellRendererComponent(JTable table,
              Object value, boolean isSelected, boolean hasFocus,
              int nRow, int nCol)
              if (value instanceof String)
                   setText((String)value);
              // Adjust row's height
              int width = table.getColumnModel().getColumn(nCol).getWidth();
              setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(nRow) != rowHeight)
                   table.setRowHeight(nRow, rowHeight);
              this.setBackground(Color.WHITE);
              return this;

    I think Problem is between these code only
    for(int k=0;k<columnCount;k++)
                   TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();
                                                                itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);or in this renderer
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
         public TextAreaCellRenderer() {
              setEditable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
         public Component getTableCellRendererComponent(JTable table,
              Object value, boolean isSelected, boolean hasFocus,
              int nRow, int nCol)
              if (value instanceof String)
                   setText((String)value);
              // Adjust row's height
              int width = table.getColumnModel().getColumn(nCol).getWidth();
              setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(nRow) != rowHeight)
                   table.setRowHeight(nRow, rowHeight);
              this.setBackground(Color.WHITE);
              return this;
    }

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

  • Cell Editor Problem in JTable

    I have a problem using JTable. I have a requirement like each specified cell will have different editors like JtextField or Jcombobox as per some condition. I am building the rows at run time. Number of rows may vary as per condition.
    can anyone guide me what to do?
    thanks

    Override the getCellEditor(...) method to return the appropriate editor.

  • Help!!! JTable cell editor problem...

    I am having a problem with table cell editors.
    The problem is that when I click on another component
    in the frame (out side of the JTable) the cell editors's
    stopCellEditing() is not called so I get a JTable with a cell
    editor in editing mode.
    Any help?
    Thanks a lot

    It is difficult to tell what happens with FocusEvents when you are actually editing a cell and the editor is "up". I am experiencing different difficulties with the same root issue. I think the problem here is that the Java Focus Manager is consuming the focus event without propagating the event to any of the JTable components (CellEditor or JTable). I am not sure if this is exactly the case but I haven't been able to trap focus events in the Editors, Renderers or JTable anywhere. If the editor is not "up" then event handling seems to be fairly normal but when you are actually editing a cell it becomes tricky.
    However, this is a problem I fixed by placing a FocusGained event handler on the other (non JTable) component and then manually stopping editing on the JTable. In other words in the JFrame (or whatever component you are using) I added a FocusListener to the non JTable component and inside of FocusGanied() I execute:
    public void focusGained(FocusEvent e){
    table.getCellEditor().stopEditing();
    table.removeEditor();
    You could, of course, use cancelEditing() as well. You'll probably want to wrap the code with some robustness as follows to ensure that you don't get trapped by wierdness.
    public void focusGained(FocusEvent e){
    if (table.isEditing() && table.getCellEditor() != null){
    table.getCellEditor().stopEditing();
    table.removeEditor();
    This is probably not the only way to solve the problem but it was the way that worked when I encountered that issue.

  • Custom JTable cell editor problem

    I have a custom JTable cell editor which is a JPanel with 2 JtextFields, One for a name, the other for a data value. My problem lies in when the the cell is selected and then the user start typing. The JTextfield outline shows up, but there is no carat. I can only edit the cell when I click the mouse in it again. I have my isCellEditable method set to only allow editing on 2 mouse clicks, but I did try it with just returning true and had the same problem. Please help.
    Code:
    class cellValue {
    String name;
    String data;
    Color nameColor;
    Color dataColor;
    Font font;
    public cellValue(String n, String d, Color nC, Color dC, Font ff){
    name = n;
    data = d;
    nameColor = nC;
    dataColor = dC;
    font = ff;
    } //end class
    public class TextFieldCellEditor extends JPanel implements TableCellRenderer, TableCellEditor{
    private EventListenerList listenerList = new EventListenerList();
    private ChangeEvent event = new ChangeEvent(this);
    private cellValue s;
    private int e_row=0;
    private int e_col=0;
    private JTextField ta;
    private JTextField tb;
    public TextFieldCellEditor() {
    setLayout(new GridBagLayout());
    ta = new JTextField();
    tb = new JTextField();
    tb.setHorizontalAlignment(SwingConstants.RIGHT);
    add(ta, new GridBagConstraints(0,0,1,1,0.6,0.0,java.awt.GridBagConstraints.WEST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    add(new JLabel(" "),new GridBagConstraints(1,0,1,1,0.1,0.0,java.awt.GridBagConstraints.WEST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    add(tb, new GridBagConstraints(2,0,1,1,0.3,0.0,java.awt.GridBagConstraints.EAST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    } //end init
    public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected,
    boolean hasFocus,int row, int column) {
    s = (cellValue)value;
    e_row = row;
    e_col = column;
    ta.setText(s.name);
    tb.setText(s.data);
    ta.setFont(s.font);
    tb.setFont(s.font);
    ta.setForeground(s.nameColor);
    tb.setForeground(s.dataColor);
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    ta.setBackground(table.getBackground());
    tb.setBackground(table.getBackground());
    ta.setCaretColor(Color.WHITE);
    tb.setCaretColor(Color.WHITE);
    return (JComponent)(this);
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    return (getTableCellRendererComponent(table, value,isSelected, true, row, column));
    public boolean isCellEditable(EventObject e) {
    if (e instanceof MouseEvent) {
    return ((MouseEvent)e).getClickCount() >= 2;
    } return true;
    // return true;
    public boolean shouldSelectCell(EventObject anEvent) {
    return (true);
    public void cancelCellEditing() {
    public boolean stopCellEditing() {
    fireEditingStopped();
    return (true);
    public Object getCellEditorValue() {
    return (ta.getText());
    public void addCellEditorListener(CellEditorListener l){
    try {
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run() {requestFocus();}
    } catch (Exception e) {};
    listenerList.add(CellEditorListener.class, l);
    public void removeCellEditorListener(CellEditorListener l) {
    listenerList.remove(CellEditorListener.class, l);
    protected void fireEditingStopped(){
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingStopped(event);
    protected void fireEditingCanceled() {
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingCanceled(event);
    } //end class

    Thanks again for the repley.
    I tried removing the celleditorlistener and using the setSurrenderFocusOnKeystroke, but it did not work. The textfield is editable;
    I did change:
    public void addCellEditorListener(CellEditorListener l){
    try {
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run() {ta.requestFocus();}
    } catch (Exception e) {};
    listenerList.add(CellEditorListener.class, l);
    }This allows the first textfield to request focus and this seems to work. But when I highlight a cell, then start typing, the first character I type puts me into the editor, but it is lost. Example:
    I type hello
    and get ello in the cell. Then when I press enter the input is excepted and the selection goes to the next cell, but I cannot move the Highlight cursor at all, seems locked. The only way I can continue to the next cell is to use the mouse.
    You said you had a cell editor working. Would you care to share as an example. This is killing me to get this to work properly.
    Thanks again
    Dave

  • JTable cell render problem, help!

    Hi all,
    I'm trying to change the color of some cells in a JTable. I have the definition of what cell to render in a different color in a Vector. So each time the cell render is called, I check if the cell it's in my vector, and if yes I change the background color to red.
    The problem is, the result are not the desired, some cells are some times in red other times in red! Some one have an idea of what appends?
    Thanks NeuralC
    public Component getTableCellRendererComponentJTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    Component cell = super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column);
    for(int i=0;i<((LinhaRefresh)RefreshOjb.elementAt(row)).Gamas.size();i++){
    if(((column)>=((Gama)((LinhaRefresh)RefreshOjb.elementAt(row)).Gamas.elementAt(i)).inicio) & ((column) <=((Gama)((LinhaRefresh)RefreshOjb.elementAt(row)).Gamas.elementAt(i)).fim)){
    cell.setBackground(Color.red);
    return cell;
    cell.setBackground(Color.white);
    return cell;
    }

    Hi,
    AND symbol is &, and I must use it.
    I haved solved the problem, extending my cell render to a JLabel. With this and making my self the selection color everything works fine.
    Thanks for interrest.
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    JLabel lb = new JLabel((String)value);
    //Component cell = super..;
    setText((String)value);
    if(!isSelected){
    setBackground(Color.white);
    else{
    setBackground(Color.blue);
    for(int i=0;i<((LinhaRefresh)RefreshOjb.elementAt(row)).Gamas.size();i++){
    if(((column)>=((Gama)((LinhaRefresh)RefreshOjb.elementAt(row)).Gamas.elementAt(i)).inicio) & ((column) <=((Gama)((LinhaRefresh)RefreshOjb.elementAt(row)).Gamas.elementAt(i)).fim)){
    if(hasFocus){
    setToolTipText("est� dentro"+column);
    setBackground(Color.red);
    return this;

  • Problem with JTable and JPanel

    Hi,
    I'm having problems with a JTable in a JPanel. The code is basicly as follows:
    public class mainFrame extends JFrame
            public mainFrame()
                    //A menu is implemeted giving rise to the following actions:
                    public void actionPerformed(ActionEvent evt)
                            String arg = evt.getActionCommand();
                            if(arg.equals("Sit1"))
                            //cells, columnNames are initiated correctly
                            JTable table = new JTable(cells,columnNames);
                            JPanel holdingPanel = new JPanel();
                            holdingPanel.setLayout( new BorderLayout() );
                            JScrollPane scrollPane = new JScrollPane(holdingPanel);
                            holdingPanel.setBackground(Color.white);
                            holdingPanel.add(table,BorderLayout.CENTER);
                            add(scrollPane, "Center");
                            if(arg.equals("Sit2"))
                                    if(scrollPane !=null)
                                            remove(scrollPane);validate();System.out.println("ScrollPane");
                                    if(holdingPanel !=null)
                                            remove(holdingPanel);
                                    if(table !=null)
                                            remove(table);table.setVisible(false);System.out.println("table");
                            //Put other things on the holdingPanel....
            private JScrollPane scrollPane;
            private JPanel holdingPanel;
            private JTable table;
    }The problem is that the table isn't removed. When you choose another situation ( say Sit2), at first the table apparently is gone, but when you press with the mouse in the area it appeared earlier, it appears again. How do I succesfully remove the table from the panel? Removing the panel doesn't seem to be enough. Help is much appreciated...
    Best regards
    Schwartz

    If you reuse the panel and scroll pane throughout the application,
    instantiate them in the constructor, not in an often-called event
    handler. In the event handler, you only do add/remove of the table
    on to the panel. You can't remove the table from the container
    which does not directly contain it.
    if (arg.equals("Sit2")){
      holdingPanel.remove(table);
      holdingPanel.revalidate();
      holdingPanel.repaint(); //sometimes necessary
    }

  • Selection Problem with JTable

    Hello,
    i have a selection problem with JTable. I want to allow only single cell selection and additionally limit the selection to the first column.
    I preffered the style from MS Outlook Express where you can select the email accounts to edit.
    It is a table like this:
    Account name  |   Type  |   ...
    --------------|---------|---------------------
    Hotmail       |   POP3  |
    GMX           |   IMAP  |The selection should be only avaibable at 'Hotmail' or 'GMX' - not at 'POP3', 'IMAP' or as complete row selection.
    Please help me!
    Thanks.
    Warlock

    Maybe this will helpimport java.awt.*;
    import javax.swing.*;
    public class Test3 extends JFrame {
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        String[] head = {"One", "Two"};
        String[][] data = {{"R1-C1", "R1-C2"}, {"R2-C1", "R2-C2"}};
        JTable jt = new JTable(data, head);
        jt.getColumnModel().setSelectionModel(new MyTableSelectionModel());
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        jt.setCellSelectionEnabled(true);
        jt.setRowSelectionAllowed(false);
        jt.setColumnSelectionAllowed(false);
        setSize(300, 300);
        setVisible(true);
      public static void main(String[] arghs) { new Test3(); }
    class MyTableSelectionModel extends DefaultListSelectionModel {
      public void setSelectionInterval(int index0, int index1) {
        super.setSelectionInterval(0, 0);
    }

  • How to write an element in a  JTable Cell

    Probably it's a stupid question but I have this problem:
    I have a the necessity to build a JTable in which, when I edit a cell and I push a keyboard button, a new Frame opens to edit the content of the cell.
    But the problem is how to write something in the JTable cell, before setting its model. Because, I know, setCellAT() method of JTree inserts the value in the model and not in the table view. And repainting doesn't function!
    What to do??
    Thanks

    Hi there
    Depending on your table model you should normally change the "cell value" of the tablemodel.
    This could look like:
    JTable table = new JTable();
    TableModel model = table.getModel();
    int rowIndex = 0, columnIndex = 0;
    model.setValueAt("This is a test", rowIndex, columnIndex);
    The tablemodel should then fire an event to the view (i.e. JTable) and the table should be updated.
    Hope this helps you

  • How to select rows in the inner JTable rendered in an outer JTable cell

    I have wrriten the following code for creating cell specific renderer - JTable rendered in a cell of a JTable.
    table=new JTable(data,columnNames)
    public TableCellRenderer getCellRenderer(int row, int column)
    if ((row == 0) && (column == 0))
    return new ColorRenderer();
    else if((row == 1) && (column == 0))
    return new ColorRenderer1();
    else
    return super.getCellRenderer(row, column);
    ColorRenderer and ColorRenderer1 are two inner classes, which implement TableCellRenderer to draw inner JTable on the outer JTable cell, having 2 rows and 1 column each.
    Now what is happening the above code keeps executing continously, that is the classes are being initialised continously, inner JTables are rendered (drawn) continously, and this makes the application slow after some time. It throws java.lang.OutOfMemoryException.
    WHY IS IT SO??? I can't understand where's the bug..
    Any advice please???
    Moreover i want selections in inner tables and not on outer table, how can this be possible.
    I am working on this since a long time but have not yet found a way out...

    With your help i have overcome the problem of continous repeatition.
    The major problem which I am facing is, in selecting rows in the inner rendered JTables.
    I have added listener on outer JTable which select rows on the outer JTable, hence the complete inner JTable which being treated as a row, gets selected.
    The thing is i need to select the rows of inner rendered JTables,not the outer JTable.
    How to go about it??
    I have even added listener to inner rendered JTables, but only first row of every table gets selected.
    Please help....
    Thanks in advance.

  • Update jtable cell via numeric keypad

    Hi,
    I have a problem, trying to figure out how to input numbers in a jtextfield in a jtable cell, from a group of jbuttons (rendered as a numeric keypad). I can get the cell to focus, but when I click on one of the jbuttons in the keypad, the cell loses focus and nothing is printed. I can update the cell by directly typing from the keyboard; that works fine. But I'm lost when trying to do it from the touch-screen keypad. Can anyone point me in the right direction. I assume I need to attach additional listeners somewhere.
    Thanks in-advance.
    Lee

    I can get the cell to focus, Then the code for you button would need to be something like:
    String text = (String)table.getValueAt(...);
    String updated = text + button.getText();
    table.setValueAt(updated, ...);

  • Update JTable cells via setValueAt

    Hello all,
    I'm trying to implement a setValueAt method using an arrayList.....no success.What listeners should I have set up(For JTable or my table model)? I am new at this and I'm trying to update the JTable cells after a query from some db. Could anyone help?
    When trying to change the a value in the table I get these errors:
    "Exception occurred during event dispatching:
    java.lang.ClassCastException: java.lang.String
    at CachingResultSetTableModel.getValueAt(CachingResultSetTableModel.java:37)
    at javax.swing.JTable.getValueAt(JTable.java:1711)
    at javax.swing.JTable.prepareRenderer(JTable.java:3530)"
    public void setValueAt(Object avalue, int r, int c){
    if(r < cache.size()){
    row[c] = (Object[])cache.set(r, avalue);
    fireTableCellUpdated(r, c);
    }//setValueAt
    *********For reference here's the getValueAt method*************************
    public Object getValueAt(int r, int c){
    if(r < cache.size()){
    row = (Object[])cache.get(r);
    return row[c];
    else
    return null;
    }//getValueAt

    I would think that everone who starts off with JTable will have a couple of concept problems. I am also going thru this learnig curve. It looks to me ( the blind leading the blind etc) like your basic table has strange data in it. The problem is occuring when the JTable is trying to setup the data from the table model.
    I don't think its anything to do with setValueAt.
    I kept going back to TableMap, TableSorter and JDBCAdaptor examples and copying the code from them to come right.> I debug by putting a System.out .... in all the methods until I get to where the code is giving trouble.
    Good luck [email protected]
    Hello all,
    >
    I'm trying to implement a setValueAt method using an
    arrayList.....no success.What listeners should I have
    set up(For JTable or my table model)? I am new at
    this and I'm trying to update the JTable cells after a
    query from some db. Could anyone help?
    When trying to change the a value in the table I get
    these errors:
    "Exception occurred during event dispatching:
    java.lang.ClassCastException: java.lang.String
    at
    CachingResultSetTableModel.getValueAt(CachingResultSetT
    bIleModel.java:37)
    at javax.swing.JTable.getValueAt(JTable.java:1711)
    at
    javax.swing.JTable.prepareRenderer(JTable.java:3530)"
    public void setValueAt(Object avalue, int r, int c){
    if(r < cache.size()){
    row[c] = (Object[])cache.set(r, avalue);
    fireTableCellUpdated(r, c);
    }//setValueAt
    *********For reference here's the getValueAt
    method*************************
    public Object getValueAt(int r, int c){
    if(r < cache.size()){
    row = (Object[])cache.get(r);
    return row[c];
    else
    return null;
    }//getValueAt

  • Multiple JButtons inside JTable cell - Dispatch mouse clicks

    Hi.
    I know this subject has already some discussions on the forum, but I can't seem to find anything that solves my problem.
    In my application, every JTable cell is a JPanel, that using a GridLayout, places vertically several JPanel's witch using an Overlay layout contains a JLabel and a JButton.
    As you can see, its a fairly complex cell...
    Unfortunately, because I use several JButtons in several locations inside a JTable cell, sometimes I can't get the mouse clicks to make through.
    This is my Table custom renderer:
    public class TimeTableRenderer implements TableCellRenderer {
         Border unselectedBorder = null;
         Border selectedBorder = null;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                   boolean hasFocus, int row, int column) {
              if (value instanceof BlocoGrid) {
                   if (isSelected) {
                        if (selectedBorder == null)
                             selectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getSelectionBackground());
                        ((BlocoGrid) value).setBorder(selectedBorder);
                   } else {
                        if (unselectedBorder == null)
                             unselectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getBackground());
                        ((BlocoGrid) value).setBorder(unselectedBorder);
              return (Component) value;
    }and this is my custom editor (so clicks can get passed on):
    public class TimeTableEditor extends AbstractCellEditor implements TableCellEditor {
         private TimeTableRenderer render = null;
         public TimeTableEditor() {
              render = new TimeTableRenderer();
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
             if (value instanceof BlocoGrid) {
                  if (((BlocoGrid) value).barras.size() > 0) {
                       return render.getTableCellRendererComponent(table, value, isSelected, true, row, column);
             return null;
        public Object getCellEditorValue() {
            return null;
    }As you can see, both the renderer and editor return the same component that cames from the JTable model (all table values (components) only get instantiated once, so the same component is passed on to the renderer and editor).
    Is this the most correct way to get clicks to the cell component?
    Please check the screenshot below to see how the JButtons get placed inside the cell:
    http://img141.imageshack.us/my.php?image=calendarxo9.jpg
    If you need more info, please say so.
    Thanks.

    My mistake... It worked fine. The cell span code was malfunctioning. Thanks anyway.

  • Can JTable cell acts as JList?

    I was planning to create an Event Calendar view in Monthly. Currently my jTable cell extends JTextArea. My problem is that, for example, today I got 2 events display in one cell, when a user double-click the "today" cell, an edit form will pop out, if there are 2 events in one cell, how I know which events to be edit? In this case I was thinking to use JList instaed of jTextArea. so i can choose which event to be edit. Is there any example showing how to implement jTable with jList cell? or is there any other method to overcome it?

    I haven't used a JList in a JTable so far, but for a JComboBox you find a working example in the tutorial. That may give you some ideas.
    What I did use is a (read only) JTable in a JTable. So if you don't achieve your goal with JList there are alternatives.
    But wait for our table specialists to come along.

Maybe you are looking for

  • NVIDIA GeForce 8800 GS in iMac White

    Hello, is posible "NVIDIA GeForce 8800 GS" in my iMac 2.16 GHz Core 2 Duo 24" (MA456LL)? I dont have guarantee.

  • Problem with Direct to DVD VRD-MC6: Playback width wrong

    I made a DVD copy of a tape in my Sony Digital 8 Handicam DCR-TRV310, using an iLink cable, to my Direct to DVD VRD-MC6.  Play back of the DVD in my Sony Blue Ray DVD player BDP-BX510 on my Sony KDL-46WL140 Bravia TV was stretched width wise, distort

  • IPad photo issues with third party apps

    Up until recently I've had no problem with the issue I'm about to describe. When I download my raw format photos from my camera using the SD card reader I cannot view full photos in any third party apps such as the Photoshop app or any other I've tri

  • Forms Developer: ORA-12560 error message

    I am a novice Oracle 10g user, and have reached a dead-end regarding opening an existing form (.fmb) in Forms Builder. The ORA-12560 error message is generated: "TNS protocol error". Consulting OTN, I learned that the Oracle SID service is required t

  • Open JDK6 install gives me error.

    Hi, I have very new installation of Arch Linux. I tried installing OpenJDK and I got following error sudo pacman -S openjdk6 resolving dependencies... looking for inter-conflicts... Targets (2): ca-certificates-java-20110912-1  openjdk6-6.b22_1.10.4-