Edit Colors of Individual JTable Cells?

I want to make a JTable that has some blank cells for a TV program I'm writing. These blank cells will be the same color as the cells to the left of them. I wrote a ColorCellRenderer to do just this, as shown:
class ColorCellRenderer extends DefaultTableCellRenderer
    Color prevColor = Color.white;
    private Color[] colors = {Color.cyan, Color.yellow, Color.pink, Color.orange};
    public void setCellColor(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column)
        Object presValue = table.getValueAt(row,column);
        if (presValue.equals(""))
            getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column).setBackground(prevColor);
        else if (column > 0)
            getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column).setBackground(colors[column-1]);
            prevColor = colors[column-1];
}Then, in my JTable subclass, I loop through the cells, like this:
ColorCellRenderer ccr;
        for (int i = 0; i < getRowCount(); i++)
            Color prevColor = Color.white;
            for (int j = 1; j < getColumnCount(); j++)
                ccr = (ColorCellRenderer)getColumnModel().getColumn(j).getCellRenderer();
                if (j > 1 && items[i][j].equals("")) {
                    ccr.setCellColor(this, items[i][j], false, false, i, j);
                else {
                    ccr.setCellColor(this, items[i][j], false, false, i, j);
        }And of course I added my ColorCellRenderer to the updateUI() method of this JTable subclass.
The problem is, the JTable seems to only let me have one color per column. Here's what the result looks like:
http://img264.imageshack.us/img264/1397/picture3vt6.png
Anyone know why this is happening?

Nevermind, I misread a doc. I needed to override the getTableCellRendererComponent method. Here's the method, along with a screenshot of the program in all its glory:
class ColorCellRenderer extends DefaultTableCellRenderer
    private Color[] colors = {Color.cyan, Color.yellow, Color.pink, Color.orange};
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column)
        if (value.equals(""))
            Color c = colors[column-1];
            switch (column) {
                case 2:
                    c = colors[0];
                    break;
                case 3:
                    c = colors[1];
                    if (table.getValueAt(row, 2).equals(""))
                        c = colors[0];
                    break;
                case 4:
                    c = colors[2];
                    if (table.getValueAt(row, 3).equals("")) {
                        c = colors[1];
                        if (table.getValueAt(row, 2).equals(""))
                            c = colors[0];
                    break;
            super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column).setBackground(c);
        else if (column > 0)
            super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column).setBackground(colors[column-1]);
        else {
            super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column).setBackground(Color.white);
        return this;
}Screenshot:
http://img145.imageshack.us/img145/639/picture4mr4.png
That's it. For some reason the Channels column will not shrink, but I'm sure I'll figure it out.

Similar Messages

  • Dynamic colored in theh JTable cell

    Hi, All
    I am using a JTable to display a Jlable in the JTable cells.
    The lable is divided to, say 10 , sub rectangles. I would liketo fill each rectangles with different bg colors depending on the data I received. I tried to use html in the JLable to control the color, however, it is very expensive cuase it involves a lot of string process and also it is difficult to control the dimension of those rectangles. Do anyone has any better idea to do this ?
    The cell is not necessary to be a JLable, by the way.
    Thanks in advance !

    I have never used JPanel as my table cell component, but u might want to implement performance improvements similiar to ones done in DefaultTableCellRenderer which extends JLabel.
    Here is the code extract from DefaultTableCellRenderer
    * The following methods are overridden as a performance measure to
    * to prune code-paths are often called in the case of renders
    * but which we know are unnecessary. Great care should be taken
    * when writing your own renderer to weigh the benefits and
    * drawbacks of overriding methods like these.
    * Overridden for performance reasons.
    * See the Implementation Note
    * for more information.
    public void validate() {}
    * Overridden for performance reasons.
    * See the Implementation Note
    * for more information.
    public void revalidate() {}
    * Overridden for performance reasons.
    * See the Implementation Note
    * for more information.
    public void repaint(long tm, int x, int y, int width, int height) {}
    * Overridden for performance reasons.
    * See the Implementation Note
    * for more information.
    public void repaint(Rectangle r) { }

  • Capturing JCheckBox edit from within a JTable cell

    Hey,
    I've gone through as many posts as i can from this forum and i have managed to understand quite a bit but there is just this one probelm that i have.
    What i have is a checkbox in a cell in a jtable that causes the a jpanel elsewhere to repaint in various ways depending on whether the checkbok is checked or not.
    The code below is for the table editor. The model is my table model. aCanvas is the panel being repainted. completeVisible is the array that aCanvas accesses to repaint the panel.
    The code below works perfectly after the but only after the second click. the first 2 times i click the checkbox the value printed is true and then afterwards it starts alternating and working correctly... can anyone please tell me why this is?
    thanks in andvance... :o)
    private class TSPCellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
              Boolean visible;
              JCheckBox check;
              String TEST = "TEST";
              public TSPCellEditor() {
                   check = new JCheckBox();
                   check.setActionCommand(TEST);
                   check.addActionListener(this);
              public void actionPerformed(ActionEvent e) {
                   if(TEST.equals(e.getActionCommand())) {
                        visible = new Boolean(check.isSelected());
                        fireEditingStopped();
              public Object getCellEditorValue() {
                   return visible;
              public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
                   visible = (Boolean)(value);
                   //boolean temp = visible.booleanValue();
                   //temp = !temp;
                   //visible = Boolean.valueOf(temp);
                   check.setSelected(visible.booleanValue());
    System.out.println(completeVisible[row]+" "+row);               
                   completeVisible[row] = visible.booleanValue();
                   model.setValueAt(visible, row, column);
                   aCanvas.repaint();
                   return check;
         }

    I can't answer your question, but I think a better way to implement your solution is to use a TableModelListener. An event is fired whenver the contents of the table model are changed so you can do your processing here. This [url http://forum.java.sun.com/thread.jsp?forum=57&thread=418560]thread gives a simple example.

  • Resizing the JTable Cell horizontal width

    Sir/Madam,
    How can i resize the JTable cell's horizontal width. I know the JTable's column width can be resized. I dont want to resize the entire JTable column. But i need to resize individual JTable cell's horizontal width. Thanks in advance.

    I think that's not possible. What kind of results are you expecting ? If the cells of a column are different widths, what are you going to do with the extra space of the narrower cells ?
    What are you displaying in the cells ? Maybe you can narrow the contents of the cells, and not the cells.

  • How do you change the colors of individual cells within a 2D array?

    How do you change the colors of individual cells within a 2D array of numeric indicators?
    I want the VI to check a data value and if it is failing, white out a square at a specific index coordinate.  I have it working with color boxes, but I'm not sure how to use the property node function, to change the color of individual cells, by coordinates.
    I have attached the VI using color boxes. If you run the VI, the box corresponding to the Step control should turn white.
    I want to do the same thing, using numeric indicator boxes inside the array.
    Thanks for any suggestions...
    Attachments:
    Fill DME matrix.vi ‏95 KB

    Get rid of all these sequences! That's just bad form.
    Your code has a few logical problems. Why do you create a boolean array if you later only look at the last element (Yes, the FOR loop does nothing useful, except in the last iteration because your outputs are not indexing. All other iterations are useless, you only get the result of the last array element. My guess is that you want to color the index white if at least one of the numbers is out if range. Right?
    It is an absolute nightmare to manage all your numeric labels. Just read them from a 2D array. Now you can simply find the index of the matched elements and don't have to spend hours editing case structure conditions.
    Attached is a simple example how you would do what I meant (LV7.1). Modify as needed.
    Message Edited by altenbach on 04-04-2006 02:04 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    Fill_2DME_matrixMOD.vi ‏70 KB

  • I failed to  color  JTable cells

    Hello,
    I'm trying to set the background color of JTable cells based on their content.
    For example if I edit a cell and put a R, I'd like to paint the background in Red.
    If I enter B, I want it becomes Blue, and so on.
    I tried to use a few examples found in various fora, but all failed.
    in addition, I do not understand why I should extend JLabel and not another Class ?
    Thanks for help.
    Here is a sample code (in which all cells should become red whatever is typed in).
    import javax.swing.table.*;
    import javax.swing.*;
    public class TableRenderer extends JLabel implements javax.swing.table.TableCellRenderer {
    public java.awt.Component getTableCellRendererComponent
        javax.swing.JTable table,
       Object value,
       boolean isSelected,
       boolean hasFocus,
       int row,
       int column
         setBackground(java.awt.Color.red);   // for the moment All cells will be red
         return this;
       mytable  = new javax.swing.JTable(5,5);
       TableColumn[] column = new TableColumn[5];
       TableColumnModel colModel = mytable.getColumnModel();
       for (int i=0; i <5 ;i++)
                    column[i] = colModel.getColumn( i );
                    column.setCellRenderer(new TableRenderer());

    Finally after many tries I found a good way to do what I wanted.
    If some people are interested, here is the code.
    import java.awt.*;
    import javax.swing.table.*;
    import javax.swing.*;
    class MyClass
    public class TableRenderer extends javax.swing.table.DefaultTableCellRenderer
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
         Component xx = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
            String val = (String) table.getValueAt(row, column);
            if (gegeutil.Gegetools.isEmpty(val)) super.setBackground(Color.white);
            else if(val.equals("Tournament")) super.setBackground(Color.red);
              else if(val.equals("Class"))super.setBackground(Color.orange);
              else if(val == "")           super.setBackground(Color.white);
            else super.setBackground(Color.blue);          
                   return xx;
    public TableRenderer() {
         super();
    JTable table = new JTable(nbrow, nbcolumn);
    table.setDefaultRenderer(Object.class, new TableRenderer());
    }

  • Button to change bg-color in JTable cell

    Hello!
    I would like to change the background color of a cell with a klick on a button.
    There will be 3 colors, and the selected cell are the only one thats going to change.
    How do I do that?
    Heres my code:
    import javax.swing.*;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Rectangle;
    import javax.swing.JButton;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    import javax.swing.table.TableModel;
    public class Kinna extends JFrame {
         private static final long serialVersionUID = 1L;
         private JPanel jContentPane = null;
         private JTabbedPane jTabbedPane = null;
         private JScrollPane jScrollPane = null;
         private JTable jTable = null;
         private JButton jButtonRed = null;
         private JButton jButtonGreen = null;
         private JButton jButtonBlue = null;
         private JButton jButtonNewWeek = null;
         private JButton jButtonDelWeek = null;
          * This method initializes jTabbedPane     
          * @return javax.swing.JTabbedPane     
         private JTabbedPane getJTabbedPane() {
              if (jTabbedPane == null) {
                   jTabbedPane = new JTabbedPane();
                   jTabbedPane.setBounds(new Rectangle(105, 45, 545, 488));
                   jTabbedPane.addTab(null, null, getJScrollPane(), null);
              return jTabbedPane;
          * This method initializes jScrollPane     
          * @return javax.swing.JScrollPane     
         private JScrollPane getJScrollPane() {
              if (jScrollPane == null) {
                   jScrollPane = new JScrollPane();
                   jScrollPane.setViewportView(getJTable());
              return jScrollPane;
          * This method initializes jTable     
          * @return javax.swing.JTable     
         private JTable getJTable() {
              if (jTable == null) {
                   Object[] head = {"Namn", "M�ndag", "Tisdag", "Onsdag", "Torsdag", "Fredag"};
                   Object[][] data = {{"Niklas", "9-15", "9-15", "9-15", "9-15","9-15"},
                                            {"Niklas", "9-15", "9-15", "9-15", "9-15","9-15"}};
                   jTable = new JTable(data, head);
                      // This table shades every other column yellow
              return jTable;
          * This method initializes jButtonRed     
          * @return javax.swing.JButton     
         private JButton getJButtonRed() {
              if (jButtonRed == null) {
                   jButtonRed = new JButton("R�d");
                   jButtonRed.setBounds(new Rectangle(15, 30, 76, 31));
                   jButtonRed.setText("R�d");
                   jButtonRed.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
              return jButtonRed;
          * This method initializes jButtonGreen     
          * @return javax.swing.JButton     
         private JButton getJButtonGreen() {
              if (jButtonGreen == null) {
                   jButtonGreen = new JButton("R�d");
                   jButtonGreen.setBounds(new Rectangle(15, 75, 76, 31));
                   jButtonGreen.setText("Gr�n");
              return jButtonGreen;
          * This method initializes jButtonBlue     
          * @return javax.swing.JButton     
         private JButton getJButtonBlue() {
              if (jButtonBlue == null) {
                   jButtonBlue = new JButton("R�d");
                   jButtonBlue.setBounds(new Rectangle(15, 120, 76, 31));
                   jButtonBlue.setText("Bl�");
              return jButtonBlue;
          * This method initializes jButtonNewWeek     
          * @return javax.swing.JButton     
         private JButton getJButtonNewWeek() {
              if (jButtonNewWeek == null) {
                   jButtonNewWeek = new JButton();
                   jButtonNewWeek.setBounds(new Rectangle(270, 0, 91, 31));
                   jButtonNewWeek.setText("Ny Vecka");
                   jButtonNewWeek.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             System.out.println("actionPerformed()");
                             int i = getJTabbedPane().getSelectedIndex() + 1;
                             String tab = "Index: " + i;
                             getJTabbedPane().addTab(tab, new JLabel("Hello"));
                             getJTabbedPane().setSelectedIndex(getJTabbedPane().getTabCount()-1);
              return jButtonNewWeek;
          * This method initializes jButtonDelWeek     
          * @return javax.swing.JButton     
         private JButton getJButtonDelWeek() {
              if (jButtonDelWeek == null) {
                   jButtonDelWeek = new JButton();
                   jButtonDelWeek.setBounds(new Rectangle(375, 0, 121, 31));
                   jButtonDelWeek.setText("Ta bort vecka");
                   jButtonDelWeek.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             System.out.println("actionPerformed()");
                             getJTabbedPane().removeTabAt(getJTabbedPane().getSelectedIndex());
              return jButtonDelWeek;
          * @param args
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        Kinna thisClass = new Kinna();
                        thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        thisClass.setVisible(true);
          * This is the default constructor
         public Kinna() {
              super();
              initialize();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setSize(670, 580);
              this.setContentPane(getJContentPane());
              this.setTitle("JFrame");
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(null);
                   jContentPane.add(getJTabbedPane(), null);
                   jContentPane.add(getJButtonRed(), null);
                   jContentPane.add(getJButtonGreen(), null);
                   jContentPane.add(getJButtonBlue(), null);
                   jContentPane.add(getJButtonNewWeek(), null);
                   jContentPane.add(getJButtonDelWeek(), null);
              return jContentPane;
    }  //  @jve:decl-index=0:visual-constraint="29,25"

    If you have a different color for every cell in the table, then maybe it would be easier to store a custom Object in the TableModel that has two pieces of information:
    a) the text to be displayed
    b) the background color of the text.
    Then you can write a custom renderer that uses both pieces of information to renderer the cell correctly.
    Here is an untested example of what the custom renderer might look like:
    class ColorRenderer extends DefaultTableCellRenderer
         public Component getTableCellRendererComponent(
                   JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
              super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
              CustomObject custom = (CustomObject)value;
              setText( custom.getText() );
              if (!isSelected)
                   setBackground( custom.getBackground() );
              return this;
    }

  • JTable cell background color

    Hi All,
    I want to change the background color of the same of the cells in jTabel. How can I do that.
    Like, I want to keep 3 cells in red color. Another 2 cells in in green color, And keep other cell background color to default.
    Also I want to change the background color of the cell, with different selection in other component(like jTree, jList).
    Thank you,
    Avin Patel

    The same cell renderer is used by all cells of the table. You can't just set the background color of a cell once. You have to reset it every time the cell renderer is called (depending on which row/column you are being asked to render). Here is an example:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableCell extends JFrame
         JTable table;
         public TableCell()
              Object[][] data = { {"1", "A"}, {"2", "B"}, {"3", "C"}, {"4", "D"}  };
              String[] columnNames = {"Number","Letter"};
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              table = new JTable( model );
              //  Set default cell renderer
              TableCellRenderer renderer = new TestRenderer();
              table.setDefaultRenderer(Object.class, renderer);
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableCell frame = new TableCell();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
         class TestRenderer extends DefaultTableCellRenderer
              public Component getTableCellRendererComponent(
                   JTable table,
                   Object value,
                   boolean isSelected,
                   boolean hasFocus,
                   int row,
                   int column)
                   super.getTableCellRendererComponent(table,
                   value, isSelected, hasFocus, row, column);
                   if (column == 0)
                        setHorizontalAlignment( LEFT );
                        setBackground( Color.blue );
                   else
                        setHorizontalAlignment( RIGHT );
                        setBackground( Color.green );
                   if (row == 1)
                        setBackground( Color.red );
                   return this;
    }

  • JTable cell edits return to original values

    Hi
    I am making some progress with using AbstractTableModel, however I have a problem whereby any edits that I make to cells within the table are being lost when I add a new row��the original values are re-appearing.
    I have searched through the forum looking for a solution but with no success thus far.
    I believe that the solution lies with the fireTableDataChanged() method but thus far I have had no success. My problem (I believe) is that I cannot work out how to fire it when a user leaves the newly edited cell.
    The method that adds the new rows is shown below and is called from a button on the Frame that houses the jTable. I have tried firing the method from here, hoping that all table edits will persist, but unfortunately they still disappear.
    public void fillTable()
            if(c > 0)
                for (int i = 0; i < c; i = i + 1)
                    this.setValueAt(((JobItemClass) items.get(i)).getItemNumber(), i, 0);
                    this.setValueAt(((JobItemClass) items.get(i)).getDescription(), i, 1);
                    this.setValueAt(((JobItemClass) items.get(i)).getCostPerItem(), i, 2);
                    this.setValueAt(((JobItemClass) items.get(i)).getQuantity(), i, 3);
        public void addRow()
            newItem = new JobItemClass();   //Create an object to hold the new row defsault values
            newItem.setItemNumber(c + 1);
            newItem.setDescription("");
            newItem.setCostPerItem(0.0);
            newItem.setQuantity(0);
            items.add(c, newItem);          //Add the default object to the array
            c = c + 1;                      //Update the variable holding the array size
            table = new Object[c][4];       //Increase the size of the object that acts as the table
            fireTableRowsInserted(c, c);    //Alert the object acting as the table that there is a new row
            fillTable();                    //Refresh the display to reflect the new row default values      
        }As always, any help greatly appreciated
    GB

    Thanks again for the replies people.
    I decided to edit this message and post updated code which can be seen below. This is a result of re-reading the helpfull advice from both azukov and camickr who took the time to respond to my initial request for help. I still have to work out how to validate user input but am sure that the tableChanged method will be the key.
    A simple tutorial also provided great assistance, especially helping eith the implementation of the TableModelListener. I have provided a link to the tutorial here:
    http://www.javalobby.org/articles/jtable/
    The coding was carried out in netbeans 5.5, libraries have not been included.
    Here is my updated code......table model first:
    public class MyJobItemTableModel extends AbstractTableModel
        JobItemClass newItem;   //Procides a default record when nothing available
        int jobNo;
        int c;
        ArrayList items;        //Stores the objects that provide the records
        public MyJobItemTableModel(int j)
            jobNo = j;
            items = (new JobAllItems(jobNo)).getItems();
            c = items.size();
        String columnName[] = { "Item Number", "Item Description", "Cost per item", "Quantity" };       
        Class columnType[] = { Integer.class, String.class, Double.class, Integer.class };
        /**************************This method probably now redundant************************
        public void storeCellValue(int row, int col)
            if(col == 0)
                ((JobItemClass) items.get(row)).setItemNumber((Integer) this.getValueAt(row, col));
            if(col == 1)
                ((JobItemClass) items.get(row)).setDescription((String) this.getValueAt(row, col));
            if(col == 2)
                ((JobItemClass) items.get(row)).setCostPerItem((Double) this.getValueAt(row, col));
            if(col == 3)
                ((JobItemClass) items.get(row)).setQuantity((Integer) this.getValueAt(row, col));
        public void addRow()
            c = c + 1;                          //Update the variable holding the array size
            newItem = new JobItemClass();       //Create a default object to fill the new row
            newItem.setItemNumber(c);
            newItem.setDescription("");
            newItem.setCostPerItem(0.0);
            newItem.setQuantity(0);
            items.add(c-1, newItem);
            this.fireTableRowsInserted(c, c);   //Update the display to show the added row.
        public int getColumnCount()
            return 4;
        public int getRowCount()
            return items.size();
        public Object getValueAt(int r, int c)
            JobItemClass jic = (JobItemClass) items.get(r);
            switch(c)
                case 0:
                    return jic.getItemNumber();
                case 1:
                    return jic.getDescription();
                case 2:
                    return jic.getCostPerItem();
                case 3:
                    return jic.getQuantity();
                default:
                    return new Object();               
        public String getColumnName(int column)
            return columnName[column];
        public Class getColumnClass(int c)
            return columnType[c];
        public boolean hasNoItems()
            if(items.size() == 0)
                return true;
            else
                return false;
        public boolean isCellEditable(int r, int c)
            return true;
        public void setValueAt(Object aValue, int r, int c)
            JobItemClass jic = (JobItemClass) items.get(r);
            switch(c)
                case 0:
                    jic.setItemNumber((Integer)aValue);
                    break;
                case 1:
                    jic.setDescription((String)aValue);
                    break;
                case 2:
                    jic.setCostPerItem((Double)aValue);
                    break;
                case 3:
                    jic.setQuantity((Integer)aValue);
                    break;              
            fireTableCellUpdated(r, c);
    }......and now the view (what the user sees)
    public class ViewItems extends javax.swing.JPanel
        protected MyJobItemTableModel myModel;
        /** Creates new form ViewItems */
        public ViewItems()
            initComponents();
        public void createTable(int jobNo)
            myModel = new MyJobItemTableModel(jobNo);
            myModel.addTableModelListener(new ViewItems.ViewItemsTableModelListener());
            jTable1.setModel(myModel);
            //jTable1.setSurrendersFocusOnKeystroke(true);  //not sure what this does
            if (myModel.hasNoItems())
                myModel.addRow();          
            public void run(int jobNo)
                createTable(jobNo);
                try
                    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                    JFrame frame = new JFrame("Invoice Breakdown");
                    frame.addWindowListener(new WindowAdapter()
                        public void windowClosing(WindowEvent evt)
                            setVisible(false);
                    frame.getContentPane().add(this);
                    frame.pack();
                    frame.setVisible(true);
                catch (Exception e)
                    e.printStackTrace();
            /**This class is required in order to respond to any changes that happen
             * to the table or data within, i.e. the user editing data in a cell.
             * The tablemodel (MyJobItemTableModel) will 'fire' the event and the
             * tableChanged() method will be executed.
            public class ViewItemsTableModelListener implements TableModelListener
                public void tableChanged(TableModelEvent evt)
                    if (evt.getType() == TableModelEvent.UPDATE)
                        int column = evt.getColumn();
                        int row = evt.getFirstRow();
                        System.out.println("row: " + row + " column: " + column);
                        jTable1.setColumnSelectionInterval(column + 1, column + 1);
                        jTable1.setRowSelectionInterval(row, row);
            /** This method is called from within the constructor to
             * initialize the form.
             * WARNING: Do NOT modify this code. The content of this method is
             * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents()
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();
            btnAddItem = new javax.swing.JButton();
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][]
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String []
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane1.setViewportView(jTable1);
            btnAddItem.setText("Add Item");
            btnAddItem.addActionListener(new java.awt.event.ActionListener()
                public void actionPerformed(java.awt.event.ActionEvent evt)
                    btnAddItemActionPerformed(evt);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(layout.createSequentialGroup()
                            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 589, Short.MAX_VALUE)
                            .addContainerGap())
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .add(btnAddItem)
                            .add(264, 264, 264))))
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 163, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(49, 49, 49)
                    .add(btnAddItem)
                    .addContainerGap(54, Short.MAX_VALUE))
        }// </editor-fold>                       
        private void btnAddItemActionPerformed(java.awt.event.ActionEvent evt)                                          
            ViewItems.this.myModel.addRow();
        // Variables declaration - do not modify                    
        private javax.swing.JButton btnAddItem;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        // End of variables declaration                  
        }Edited by: greenockboy on Oct 15, 2007 8:17 PM

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

  • Start or stop edit jtable cell editing

    Hello,
    I got a problem with the jtable DefaultModel isCellEditable.
    If I set the IsCellEditable to false, I would not be able to enable the cell selection as and when I want it.
    What I have in mind is the add a mouselister so that if the user select a row using fast left mouse click like the procedure shown below
    private class MouseClickHandler extends MouseAdapter {
    public void mouseClicked(MouseEvent event) {
    int no_mouseclick = 0;
    no_mouseclick = event.getClickCount();
    if (no_mouseclick >= 2) {
    int cur_row = 0;
    cur_row = table.getSelectedRow();
    // table.setColumnSelectionAllowed(true);
    // table.setRowSelectionAllowed(true);
    for (int i=0;i<table.getColumnCount();i++){
    table.editCellAt(cur_row,i);
    System.out.println("mouse row--->" + cur_row);
    I could overwrite the IsCellEditable to true to enable that particular or cell contains in that row to be able to accept input and overwrite any data which in my case obtained from the Sql database a sort of like input module using tabulation . I am also thinking of using text component or combobox to display the value for user selection , but I do not know how to enable a particular cell for editing if the Jtable created is using a non-editable DefaultModel. If I set the IsCellEditable to true, every single cell would be enable for editing , and this defeat the purpose of enable user input only upon double mouseclicks.
    By the way , I am interested to know how to track the data changes in the cell within the jtable so that only those have been modified are notify from the Table model and updated into the Sql table
    Could anyone of you out there provide some hints please
    Thanks

    Hello,
    Tablemodellistener could detect the changes in the data, how about the backend database updating and transactional activity that must be associated with the data changes?
    What is on my mind is that , the moment there is changes in the data detected by the TableModellistener, whatever records associated with or brougt up by Jtable would be all deleted from the database and then follow by the new set of new records to be inserted into the database. The disadvantage of this method is that everytime the backend database connection and activity need to be executed the moment there is a change in the data in the jtable cell. For example the user may be just amendment to only one cell , but all the records associated need to be deleted and then inserted again.
    Perhaps there are better solution to deal with Jtable and JDBC backend connection where in this case, I am using JDO to undertake the database activity like the observable modelling .
    Could someone provide the hint please
    Thank

  • Edit a JTable cell by clicking at it once - is it possible?

    If I want to edit a cell in a JTable, I have to doubleclick on it. Is it possible to set the JTable cells to be in edit mode by just clicking at the cells once?

    Did you search the forums?? How about something like "jtable-edit-single-click".

  • Color code strips in JTable cell

    Hi,
    i want a table which has color codes in a cell like this [http://cid-bc2f07e59ddd1ff9.skydrive.live.com/self.aspx/ImageForJTable/tableImage.bmp]
    I this small vertical color bar comes in very first cell.
    How should i make this working.
    I will be highly gracefull to you........

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableTest {
      public TableTest() {
        String[] columnNames = {"FileName", "Integer"};
        Object[][] data = {
          {new FileName("AAA.jpg", Color.YELLOW), 2},
          {new FileName("BBB.png", Color.GREEN), 1},
          {new FileName("CCC.jpg", Color.RED), -1},
        DefaultTableModel model = new DefaultTableModel(data, columnNames) {
          @Override public Class<?> getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        JTable table = new JTable(model);
        table.setDefaultRenderer(FileName.class, new FileNameCellRenderer());
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JScrollPane(table));
        frame.setSize(320, 160);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      static class FileNameCellRenderer extends DefaultTableCellRenderer {
        public Component getTableCellRendererComponent(JTable table, Object v,
               boolean isSelected, boolean hasFocus, int row, int column) {
          super.getTableCellRendererComponent(
            table, v, isSelected, hasFocus, row, column);
          FileName fn = (FileName)v;
          setBorder(BorderFactory.createMatteBorder(0,2,0,0,fn.color));
          return this;
      static class FileName{
        public final Color color;
        public final String label;
        FileName(String l, Color c) {
          this.label = l;
          this.color = c;
        @Override public String toString() {
          return label;
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          @Override public void run() {
            new TableTest();
    }

  • Code to change JTable cell color not working

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

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

  • Problem when setting JTable cell color.

    hello,
    when I setting color for particular table cell, it sets.
    but, when I click another row (another cell) , the color of the previous cell disabled and it visible only when I click that cells row.
    how can I permanatly set the color for the rows depends on input data.
    for example,
    if a device is connected, I want to give the cell color GREEN.
    if device is not connected , i want to give the color as RED.
    thank you.

    but, when I click another row (another cell) , the color of the previous cell disabled and it visible only when I click that cells row.It appears you applied color to cell editor.
    tableObj.getComponentAt(x,y).setForeground(Color.red);
    tableObj.getComponentAt(x,y).setBackground(Color.red); or could be solved properl if you post the code

Maybe you are looking for

  • Process not firing

    I have a form which I create manual process for (1 for create, delete and change). They are all seperate buttons on the form and set to fire with process point 'On Submit - After computations' and there was also a condition set for 'when button press

  • Weird OLAP Partition Error

    16:49:12 ***Error Occured in BUILD_DRIVER: In __XML_SEQUENTIAL_LOADER: In __XML_MNG_PARTITIONS: In __XML_MNG_REG_PARTITION: In __XML_CRT_REG_PARTITION_ITEM: AW_OWNER.AW_TEST!TEST_DIMENSION_3 appears more than once in the dimension list. (It is also a

  • Design my own button in JFileChooser

    Hi I want my button in JFileChooser to give me the path to the directory that is selected. The thing is that I want my "save button" to do what my cancel button does. How do I do that. I cant press the "save button" if i dont select a file or a catol

  • IMovie file structure help

    Hi there. First of all, I cannot confirm whether this is for IMovie '11 or not but I had to choose a version to post. So I usually work in FCP and a client sends me some footage they had shot. I thought I was getting QT files but what I received was

  • How can I install iWeb 06 on a new computer running Leopard ?

    My site is built with iWeb 06. I have a fairly new 24" iMac running Leopard with iWeb 08 pre-installed. I don't want to risk rebuilding my entire site right now. Is there any way I can install just iWeb 06 so I continue editing my site with a program