JTable Cell Value needs to hided

Hi,
I have 5 columns in a JTable. The first column is a checkbox. The second column is non editable. The third, fourth and fifth columns are editable. Whan I click a check box, I am performing a database operation and based on the output, I am setting values to for the column 3, 4 and 5.
My requirement: I need to perform the database operation only for the first time of the check box click. If I uncheck the checkbox, the values in column 3, 4 and 5 needs to be disappeared. If I check the check box again, I need the values to be visible. Basically, I will do database calls only for the first time. From second time onwards, I need to just hide the text in the particular cells (if the checkbox is unchecked) and make the cell values visible (if the checkbox is checked) In JTable API, there are no methods to hide a cell value or I am unable to figure it out. Please help me.
Regards
subbu

Alirght here is some code. This is a bit messy but I guess the solution is clear. It make use of a combination of renderers, ie the Sun's DefaultTableCellRenderer (for the first column to get the checkboxes) and a custom renderer for the rest of the columns.
Also, a MouseListener is added so that on clicking the first column, a repaint is forced to ensure the values in the cells disappear.
* @(#)CheckableRow.java
* @author icewalker2g
* @version 1.00 2007/12/27
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.util.*;
import java.io.*;
public class CheckableRow extends JFrame {
    public JTable table;
    public DefaultTableModel model;
    public CheckableRow() {
        super("Checkable Row");
        createUI();
    public void createUI() {
        Vector<String> cols = new Vector<String>();
            cols.addElement("Col 1");
            cols.addElement("Col 2");
            cols.addElement("Col 3");
            cols.addElement("Col 4");
            cols.addElement("Col 5");
        Vector<Object> rows = new Vector<Object>();
        model = new DefaultTableModel(rows, cols);
        for(int i = 0; i < 5; i++) {
            Vector<Object> row = new Vector<Object>();
                row.addElement( false );
                row.addElement("Data");
                row.addElement("Col 3 Data " + (i+1));
                row.addElement("Col 4 Data " + (i+1));
                row.addElement("Col 5 Data " + (i+1));
            model.addRow( row );
        table = new JTable(model) {
            CellValueRenderer renderer = new CellValueRenderer();
            public TableCellRenderer getCellRenderer(int row, int col) {
                if(col > 1) {
                    return renderer;   
                return super.getCellRenderer(row, col);
            public Class getColumnClass(int col) {
                if( col == 0) {
                    return Boolean.class;
                return super.getColumnClass(col);
            public boolean isCellEditable(int row, int col) {
                if( col != 1 ){
                    return true;
                return false;
        table.addMouseListener( new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if( table.columnAtPoint( e.getPoint() ) == 0 ) {
                    table.repaint();
        getContentPane().add( new JScrollPane(table), BorderLayout.CENTER );
        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    public class CellValueRenderer extends DefaultTableCellRenderer {
        public CellValueRenderer() {
            super();
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
            boolean hasFocus, int row, int col) {
            DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
            if( table.getValueAt(row, 0).toString().equals("true") && col > 1) {
                renderer.setText("");
            } else {
                renderer.setText( value == null ? "" : value.toString() );
            return renderer;
    public static void main(String[] args) {
        new CheckableRow();
}ICE

Similar Messages

  • JTable cell value doesn't change with user input

    I'm making a program that uses a custom table model (extends AbstractTableModel). The problem is when I type a value in one of the table cells, then press enter (or click outside the cell), the value goes back to what it was originally. So for example, a cell has "oldvalue", I type in "newvalue", press enter, and now the cell still reads "oldvalue". I figured the renderer would automatically update the cell by calling MyTableModel.setValueAt (...), but maybe I need a listener to do this? let me know. thanks

    alright, well basically I'm making a database manager
    and thought it would be easier to extend
    AbstractTableModel and then do all the queries inside
    the methods instead of listening for events. Second
    thing, I put a debug statement and setValueAt never
    gets called when you type in a new cell value. How
    does it update the cell then is my question?It's your TableModel bug but a much better advice would be that you should use
    DefaultTableModel instead of extending AbstractTableModel. The DefaultTableModel
    is usually more than enough for an ordinary JTable application.
    The simplest and standard way of handling DB data from JTable is updating
    vectors for DefaultTableModel data with your new DB data set. You don't need
    to worry about low-level event firing, cell editor control etc. if you use
    DefaultTableModel. See API documentation of DefaultTableModel closely.

  • Programatically change( edit?? ) JTable cell value

    If my user changes the value in cell 'A', I'd like to change the value in cell 'B' to the results of a calculation performed using the new value in A with the present ( prior to changing ) value in B.
    Example:
    Cell: suggested_sell_price
    Cell: cost_this_item
    A change in the cost_this_item cell would be reflected in the suggested_sell_price,(upon hitting enter the values are stored in the DB)
    Any suggestions would be greatly appreciated,

    Thanks for the suggestions. I'm posting a test program of what I have at the moment, it has some of the behavior I'm looking for, but I can't seem to get the new value of an aedited cell and set the table model with the new value.
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class TE extends JFrame
         String[] cols = {"VAL_1", "VAL_2", "VAL_3"};
         Object[][] filler = {
                                       {new Double(100.00), new Double(100.00), new Double(100.00)},
                                       {new Double(200.00), new Double(200.00), new Double(200.00)},
                                       {new Double(400.00), new Double(400.00), new Double(400.00)}
         JTable table;
         TE(String title)
                   super(title);
                   this.setDefaultCloseOperation(EXIT_ON_CLOSE);
                   MTM mtm = new MTM(3, cols.length);
                   mtm.setColumnIdentifiers(cols);
                   int nRows = filler.length;
                   for(int i = 0; i < nRows; ++i)
                             mtm.setValueAt(filler[0], 0, i);
                             mtm.setValueAt(filler[1][i], 1, i);
                             mtm.setValueAt(filler[2][i], 2, i);
                   table = new JTable(mtm);
                   table.getColumnModel().getColumn(1).setCellEditor(new SimpleCellEditor());
                   table.getColumnModel().getColumn(2).setCellEditor(new SimpleCellEditor());
                   //table.getColumnModel().getColumn(2).setCellEditor(new SimpleCellEditor());
                   JScrollPane jsp = new JScrollPane(table);
                   Container c = getContentPane();
                   c.add(jsp);
                   setSize(300,300);
                   setVisible(true);
         class MyMouseListener extends MouseAdapter
                   public void mouseClicked(MouseEvent e)
                        if(e.getClickCount() == 2)
                                  table.setValueAt("QQQQQQQ", 1,1);
    class SimpleCellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener
         JTextField tf = new JTextField();
         TableModel tm = table.getModel();
         protected EventListenerList listenerList = new EventListenerList();
         protected ChangeEvent changeEvent = new ChangeEvent(this);
         public SimpleCellEditor()
                   super();                              
                   tf.addMouseListener(new MyMouseListener());
                   tf.addActionListener(this);
    public void addCellEditorListener(CellEditorListener listener) {
    listenerList.add(CellEditorListener.class, listener);
    public void removeCellEditorListener(CellEditorListener listener) {
    listenerList.remove(CellEditorListener.class, listener);
    protected void fireEditingStopped()
              CellEditorListener listener;
              Object[] listeners = listenerList.getListenerList();
              for (int i = 0; i < listeners.length; i++)
                   if (listeners[i] == CellEditorListener.class)
                             listener = (CellEditorListener) listeners[i + 1];
                             listener.editingStopped(changeEvent);
    protected void fireEditingCanceled()
         CellEditorListener listener;
              Object[] listeners = listenerList.getListenerList();
                   for (int i = 0; i < listeners.length; i++)
                   if (listeners[i] == CellEditorListener.class)
                        listener = (CellEditorListener) listeners[i + 1];
                        listener.editingCanceled(changeEvent);
    public void cancelCellEditing()
              fireEditingCanceled();
    public boolean stopCellEditing()
              fireEditingStopped();
              return true;
    public boolean isCellEditable(EventObject event)
              return true;
         public boolean shouldSelectCell(EventObject event)
         return true;
    public Object getCellEditorValue()
         return tf.getText();
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
         if(tf.hasFocus() == true)
                   tf.setBackground(Color.CYAN);
              return tf;
         public void actionPerformed(ActionEvent e)
              int row = table.getSelectedRow();
              int col = table.getSelectedColumn();
              double nVal = 0.00;
              Object currCostVal;
              Object currSellVal;
              Double costVal;
              Double sellVal;
              double newSellVal;
              double currentCost;
              if(table.getSelectedColumn() == 1)
                   currCostVal = table.getValueAt(row, col+1);
                   currSellVal = table.getValueAt(row, col);
                   costVal = new Double(currCostVal.toString());
                   currentCost = costVal.doubleValue();
                   sellVal = new Double(currSellVal.toString());
                   newSellVal = sellVal.doubleValue();
                   nVal = newSellVal*currentCost*100/100;
                   System.out.println("Recommended sell-price after change: " + nVal);
              }else if(table.getSelectedColumn() == 2 )
                        currCostVal = table.getValueAt(row, col);
                        currSellVal = table.getValueAt(row, col-1);
                        costVal = new Double(currCostVal.toString());
                        currentCost = costVal.doubleValue();
                        sellVal = new Double(currSellVal.toString());
                        newSellVal = sellVal.doubleValue();
                        nVal = newSellVal*currentCost*100/100;
                        System.out.println("Recommended sell-price after change: " + nVal);
                        System.out.println("Cost column selected " + nVal);
    }// end simple cell editor
    class MTM extends DefaultTableModel
              MTM(int rows, int cols)
                        super(rows, cols);
    public static void main(String args[])
              TE te = new TE("Test of table cell update");

  • JTable cell value

    I have a custom cell renderer for JTable, and this cell renderer is also a listener for some event. The cell renderer receives new value as events, since it is a listener. The cell renderer must upadte this value as a table cell. Simple call this.setText does not work, as it must somehow call the "getTableCellRendererComponent" method of the TableCellRenderer interface that it implements. How can the cell renderer force the table to update itself, as the cell renderer has received his new value. What will be a good approach here?
    TIA,
    - Manish

    Manish -
    Would you be able to post your idea?
    I have a column in a table that I added
    a check box to so that the user can select
    or deselect the data. Sometimes when
    the check box is selected or deselected it
    doesn't register until I click another field.
    Would your idea work to correct this?
    Thanks!

  • How to make Jtable cell empty onClick?

    Hi All,
    I have one requirement where I need to make the Jtable cell value empty on click or tab event. So, User does not have to do back space and delete whole string to edit that cell.
    Any idea?
    Thanks in advance.

    Hi camickr,
    Thanks for that reply. It did not work for me but Here is the thing.
    My requirement was : Client does not want to do back space in order do edit cell value when that cell clicked.
    I tried find the solution that, i can make that cell area as selected when it is clicked. my problem is solved. So, I tried to use Table select all editor.
    But here is what i found ......
    If I want that cell area selected, I need to do one more click(3 clicks at the same time) to select the value of that cell & I can put my new value without doing back space(stupid client requirement)
    Thanks for your help

  • Hiding a cell value in Jtable

    Is it possible to hide a cell value in a JTable?. The value should be present in the JTable but just hidden
    tnx

    Yes, there are a few ways to do this. I'm sure there are others, but here are 2 quick ways:
    1. When the cell value (Object ) is being rendered, it's toString() method is called. Create a subclass of whatever Object you are using in cells and override the toString() method.
    2. Create you own cell renderer and then you can renderer the contents of a cell however you wish.
    Regards,
    Muel.

  • Touble getting cell values from jTable

    Hi everybody, I need some hepl to understand this problem.
    I have jtable and I�m trying to get the values from the cells (first in the jOption panel then to jLabel and to jTextFields).
    All cell values are shown perfectly in the JOptionPanel.
    But I can�t get any values to the jLabel from the first column(0) no matter what row I press from the firts column.
    It gives me this error
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Integer
         at taulukko3.FTaulukko3.jTable1_mouseClicked(FTaulukko3.java:163)Here is my code where I think the problem is:
    public void jTable1_mouseClicked(MouseEvent e) {
       JOptionPane.showMessageDialog(this,jTable1.getValueAt(jTable1.getSelectedRow(),jTable1.getSelectedColumn()));
          try{
          int valittusarake = jTable1.getSelectedColumn();
           String tulos= "";
           if (valittusarake == 0) {
             tulos = (String) jTable1.getValueAt(jTable1.getSelectedRow(),
                                                      jTable1.getSelectedColumn());
            jLabel1.setText(tulos);
           if (valittusarake == 1) {
             tulos = (String) jTable1.getValueAt(jTable1.getSelectedRow(),
                                                       jTable1.getSelectedColumn());
             jTextField1.setText(tulos);
           if (valittusarake == 2) {
             tulos = (String) jTable1.getValueAt(jTable1.getSelectedRow(),
                                                       jTable1.getSelectedColumn());
             jTextField2.setText(tulos);
    }

    Hi everybody
    I got it workin by making this change to my code:
          if (valittusarake == 0) {
             Object tulos1 = jTable1.getValueAt(jTable1.getSelectedRow(),jTable1.getSelectedColumn());
             jLabel1.setText(tulos1.toString());
          }

  • Shading part of a JTable Cell dependent upon the value of the cell

    Hi
    Was hoping some one woudl be able to provide some help with this. I'm trying to create a renderer that will "shade" part of a JTable cell's background depending upon the value in the cell as a percentage (E.g. if the cell contains 0.25 then a quarter of the cell background will be shaded)
    What I've got so far is a renderer which will draw a rectangle whose width is the relevant percentage of the cell's width. (i.e. the width of the column) based on something similar I found in the forum but the part I'm struggling with is getting it to draw this rectangle in any cell other than the first cell. I've tried using .getCellRect(...) to get the x and y position of the cell to draw the rectangle but I still can't make it work.
    The code for my renderer as it stands is:
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    public class PercentageRepresentationRenderer extends JLabel implements TableCellRenderer{
         double percentageValue;
         double rectWidth;
         double rectHeight;
         JTable table;
         int row;
         int column;
         int x;
         int y;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              if (value instanceof Number)
                   this.table = table;
                   this.row = row;
                   this.column = column;
                   Number numValue = (Number)value;
                   percentageValue = numValue.doubleValue();
                   rectHeight = table.getRowHeight(row);
                   rectWidth = percentageValue * table.getColumnModel().getColumn(column).getWidth();
              return this;
         public void paintComponent(Graphics g) {
            x = table.getCellRect(row, column, false).x;
            y = table.getCellRect(row, column, false).y;
              setOpaque(false);
            Graphics2D g2d = (Graphics2D)g;
            g2d.fillRect(x,y, new Double(rectWidth).intValue(), new Double(rectHeight).intValue());
            super.paintComponent(g);
    }and the following code produces a runnable example:
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    public class PercentageTestTable extends JFrame {
         public PercentageTestTable()
              Object[] columnNames = new Object[]{"A","B"};
              Object[][] tableData = new Object[][]{{0.25,0.5},{0.75,1.0}};
              DefaultTableModel testModel = new DefaultTableModel(tableData,columnNames);
              JTable test = new JTable(testModel);
              test.setDefaultRenderer(Object.class, new PercentageRepresentationRenderer());
              JScrollPane scroll = new JScrollPane();
              scroll.getViewport().add(test);
              add(scroll);
         public static void main(String[] args)
              PercentageTestTable testTable = new PercentageTestTable();
              testTable.pack();
              testTable.setVisible(true);
              testTable.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }If anyone could help or point me in the right direction, I'd appreciate it.
    Ruanae

    This is an example I published some while ago -
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Fred120 extends JPanel
        static final Object[][] tableData =
            {1, new Double(10.0)},
            {2, new Double(20.0)},
            {3, new Double(50.0)},
            {4, new Double(10.0)},
            {5, new Double(95.0)},
            {6, new Double(60.0)},
        static final Object[] headers =
            "One",
            "Two",
        public Fred120() throws Exception
            super(new BorderLayout());
            final DefaultTableModel model = new DefaultTableModel(tableData, headers);
            final JTable table = new JTable(model);
            table.getColumnModel().getColumn(1).setCellRenderer( new LocalCellRenderer(120.0));
            add(table);
            add(table.getTableHeader(), BorderLayout.NORTH);
        public class LocalCellRenderer extends DefaultTableCellRenderer
            private double v = 0.0;
            private double maxV;
            private final JPanel renderer = new JPanel(new GridLayout(1,0))
                public void paintComponent(Graphics g)
                    super.paintComponent(g);
                    g.setColor(Color.CYAN);
                    int w = (int)(getWidth() * v / maxV + 0.5);
                    int h = getHeight();
                    g.fillRect(0, 0, w, h);
                    g.drawRect(0, 0, w, h);
            private LocalCellRenderer(double maxV)
                this.maxV = maxV;
                renderer.add(this);
                renderer.setOpaque(true);
                renderer.setBackground(Color.YELLOW);
                renderer.setBorder(null);
                setOpaque(false);
                setHorizontalAlignment(JLabel.CENTER);
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
                final JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                if (value instanceof Double)
                    v = ((Double)value).doubleValue();
                return renderer;
        public static void main(String[] args) throws Exception
            final JFrame frame = new JFrame("Fred120");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new Fred120());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }

  • Hiding Cell Value in a Table

    If a cell in a table is less than a certain value how do you make that hidden? Which then also means if a cell value is greater than a certain value it can be seen.

    Hi,
    Are Row6.ph2 and Row7.Cell3 numeric fields ?
    It seems that you're using Javascript. In this case, you should access the value of a field using rawValue (ie Row6.ph2.rawValue).
    You also need to give a relative (this.parent ...) or absolute path (xfa.resolveNode("form.table.Row7")) to access Row6 and Row7, for example :
    this.rawValue=(Number(this.parent.Row6.ph2.rawValue) + Number(this.parent.Row7.Cell3.rawValue));
    if Row6 and Row7 are in the same subform as the total field.
    After testing the script quickly, it seems that if you put the rest of the script in the layoutReady event, it works fine.
    if (this.rawValue <8) {
         this.presence = "hidden";
    } else {
         this.rawValue = this.rawValue - 8;
         this.presence = "visible";
    I don't really know why it doesn't work in the calculate event, there is no error in the javascript console ...
    Anyway, be careful with the layoutReady event though, because if you have a really big form and a lot of script in this event, this could slow the execution / display of your form.
    Regards,
    Thomas

  • Edit a JTable cell, click save button, value isn't stored in JTable

    I'm editing a JTable cell, just using default editor provided by JTable
    I click a save button elsewhere in my GUI
    The value typed into the cell so far isn't stored in the TableModel yet and so doesn't get saved.
    How can I make sure the value gets stored in the JTable in the above scenario when the JButton is pressed but before saving.
    Preferably I'd like the code with the JButton not to have to know about the JTable at all.
    Cheers,
    D

    I the forums 100s of times.Many thanks. If they had a decent search on this forum I might have found it as I did try.
    Come to think of it - Sun have completely fcukd up this forum.

  • Need help in WAD 7.0 - anaylsis item cell value as filter to another web...

    Hi ,
    I need help in WAD 7.0
    i have 2 web items, analyis item 1 & 2
    when user clicks any cell value in column xxx of analysis item1, then i need to filter the analysis item 2 values for  column xxx  , for that user clicked value.
    how do i enable this ?

    Hi.
    You can try the nxt approach:
    1. in analysis item A (first) properties define in "behaviour" -> "row selection" = "single with command".
    2. set this command to "SET_SELECTION_STATE_BY_BINDING".
    3. define "data provider affected" = your second data provider for analysis item B.
    4. in "selection binding" set needed variables to binding type "VARIABLE"
    In this case, when you select any row in analysis item A some variables will be populatd from this row and affect on analys item B (dataprovider B).
    Regards.

  • JTable cell editor ..not able to delete value in the cell

    Hello,
    I have applied Cell Editor on the JTAble. I'm able to enter value initially in the cell.
    Once I tab out of that cell, go back to the same cell, edit the value again and tab out. It still shows me old value, not the updated one.
    I'm using putClientProperty("terminateEditOnFocusLost", Boolean.TRUE) to recognise the cell value without focus lost.
    Does this cause any problem ???
    Thanks in advance
    Kapil

    then what might be the problem of value not getting deleted ??
    Code is:
    public class MyTableCellEditor extends AbstractCellEditor
    implements TableCellEditor {
    //This is the component that will handle the editing of the cell value
    private JTextField component = null;
    //This method is called when a cell value is edited by the user.
    public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int rowIndex, int vColIndex) {
    component = new JTextField();
    System.out.println("value*************** "+value);
    System.out.println("Component value*************** "+component.getText());
    if(value != null){
    component.setText(value.toString());
    else{
    component.setText("");
    // Return the configured component
    return component;
    // This method is called when editing is completed.
    // It must return the new value to be stored in the cell.
    public Object getCellEditorValue() {
    return component.getText();
    public boolean shouldSelectCell(EventObject anEvent) {
    return false;
    }

  • Can not show the JCheckBox in JTable cell

    I want to place a JCheckBox in one JTable cell, i do as below:
    i want the column "d" be a check box which indicates "true" or "false".
    String[] columnNames = {"a","b","c","d"};
    Object[][] rowData = {{"", "", "", Boolean.FALSE}};
    tableModel = new DefaultTableModel(rowData, columnNames);
    dataTable = new JTable(tableModel);
    dataTable.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(new JCheckBox()));
    But when i run it, the "d" column show the string "false" or "true", not the check box i wanted.
    I do not understand it, can you help me?
    Thank you very much!
    coral9527

    Do not use DefaultTableModel, create your own table model and you should implement the method
    getColumnClass to display the boolean as checkbox ...
    I hope the following colde snippet helps you :
    class MyModel extends AbstractTableModel {
              private String[] columnNames = {"c1",
    "c2"};
    public Object[][] data ={{Boolean.valueOf(true),"c1d1"}};
         public int getColumnCount() {
         //System.out.println("Calling getColumnCount");
         return columnNames.length;
    public int getRowCount() {
    //System.out.println("Calling row count");
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * 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();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    data[row][col] = value;
    fireTableCellUpdated(row, col);

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

  • JLabels into JTable cell

    Hi friends!
    I need to have a JTable with multiple JLabels inside its cells. I wrote a class wich implements TableCellRenderer the code is the following:
    public class JLabelCellRender extends JPanel implements  TableCellRenderer {
        Vector ObJLabelsV=new Vector();
        JLabel teste;
        public JLabelCellRender() {
            super();
        public java.awt.Component getTableCellRendererComponent(JTable table,
                Object value,
                boolean isSelected,
                boolean hasFocus,
                int row, int column) {
            Vector labels=(Vector)value;
           for(int i=0;i<labels.size();i++) {
            add((JLabel)labels.elementAt(i));
            return this;
    }I nedd each cell having a variable number of JLabels, to do this I use a Vector.
    But I need to insert and remove JLabels in the main class. Like using the method setValueAt(ob,row,col) wich modifys the text in the cell I want to modify the text and the number of JLabels.
    The problem is I don't know how to insert and remove JLabels in the cells.
    I ask if I have to re-implement the setValueAt and getValueAt methods..
    Thanks in advance for help.
    Sory for my english.:)

    You need to do something similar to this
    public class JLabelCellRender extends JPanel implements  TableCellRenderer {
        Vector ObJLabelsV=new Vector();
        JLabel teste;
        public JLabelCellRender() {
            super();
        public java.awt.Component getTableCellRendererComponent(JTable table,  Object value, boolean isSelected,
                boolean hasFocus,  int row, int column) {
           // clear all exiting items in the panel
           removeAll();
           // obtain the new information for the
            Vector labels=(Vector)value;
           for(int i=0; i < labels.size(); i++) {
            add((JLabel)labels.elementAt(i));
           // adjust the row height of the current row to display all the labels
           table.setRowHeight(row, getPreferredSize().height);
            return this;
    }Now you just need to ensure that number of labels are different for the different cells you need to display.
    ICE

Maybe you are looking for