Cell colouring in a JTable

I am stuck with this problem. I have generated a large table and inserted the results of calculations into the 2D table. My next problem is then to highlight the rows and columns that contain the highest value. I have seeked advice on this matter before but i do not understand the reply to well. I have included the program that I am stuck at and will email the rest of the program if someone is interested in looking at it.
Thanks
import ccj.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
class Jacobi4 extends JFrame
     public static double c, s, t, theta, max;
     public static double eps = 0.0000005;
     public static double total = 0.0;
     public static int p, q, i, j, r, sign;
     public static int x = 0;
     public static double [][] a = new double [50][50];
     public static String result;
     public Jacobi4(int n)
          final int WIDTH = 1000;
          final int HEIGHT = 600;
          setSize(WIDTH, HEIGHT);
          addWindowListener(new WindowCloser());
          int m = n*n*n*n;
          JTable table = new JTable(m,n+1);
          JScrollPane scrollPane = new JScrollPane(table);
          scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
          scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
          //table.setFont(new Font("Monospaced", Font.PLAIN, 12));
          Container contentPane = getContentPane();
          contentPane.add(scrollPane, "Center");
          // Generate random values for the first matrix     
          for (i=0; i<n; i++)
               for (j=0; j<n; j++)
                    a[i][j] = Numeric.randomDouble(-100, 100);
          // Prints out the values in a table
          for (i=0; i<n; i++)
               for (j=0; j<n; j++)
                    a[i][j] = a[j];
                    table.setValueAt(""+a[i][j], i, j);
          // Calculation to find the max value in the matrix          
          max = 0;
          for (i=0; i<n; i++)
               for (j=i+1; j<n; j++)
                    if (Math.abs(a[i][j]) > (max))
                         max = Math.abs(a[i][j]);
                         p=i; q=j;
          table.setValueAt("Row P : "+p, n-2,n);
          table.setValueAt("Column Q : "+q, n-1,n);
          table.setValueAt("Max value: "+max, n,n);
          calculation(n,p,q,table);
     public static void calculation(int n, int p, int q, JTable table)
          if ((n*max)>(eps))     //Checks for the termination condition
               theta = 0.5*(a[q][q] - a[p][p])/a[p][q];
                         if (theta >= 0)
                              sign = 1;
                         else
                              sign = -1;
                    if (theta == 0)
                         t = 1;     
                    else
                         t = 1/(theta + (theta*sign) * Math.sqrt(1+Math.pow(theta,2)));
                    c = 1/Math.sqrt(1 + Math.pow(t,2));
                    s = c * t;
                    //Start the rotation procedure based on the values of p and q     
                    double matrix = rotation(n,c,s,p,q,a);
                    //Print out the new matrix
                    for (int i=0; i<n; i++)
                         for (int j=0; j<n; j++)
                              a[i][j] = a[j][i];
                              table.setValueAt(""+a[i][j], ((n+1)*x)+i, j);
                    // Calculation to find the max value in the matrix          
                    max = 0;
                    for (int i=0; i<n; i++)
                         for (int j=i+1; j<n; j++)
                              if (Math.abs(a[i][j]) > (max))
                                   max = Math.abs(a[i][j]);     
                                   p=i; q=j;
                    table.setValueAt("Row P : "+p, (((n+1)*(x+1))-3),n);
                    table.setValueAt("Column Q : "+q, (((n+1)*(x+1))-2),n);
                    table.setValueAt("Max value: "+max, (((n+1)*(x+1))-1),n);
                    calculation(n,p,q,table);
          else table.setValueAt("N*Max less than eps", (((n+1)*(x+1))),n);
     public static JTextArea inputArea;
     public static JTable table;
     public static double rotation(int n,double c,double s,int p,int q, double [][]a)
          double h = c*c*a[p][p] - 2*c*s*a[p][q] + s*s*a[q][q];
          double g = s*s*a[p][p] + 2*c*s*a[p][q] + c*c*a[q][q];
          a[p][q] = c*s*(a[p][p]-a[q][q])+(c*c-s*s)*a[p][q];
          a[p][p] = h; a[q][q] = g; a[q][p] = a[p][q];
          a[p][q] = 0;     a[q][p] = 0;
          x = x+1;
          for (j=0;j<p;j++){
               h = c*a[j][p] - s*a[j][q];
               a[j][q] = s*a[j][p] + c*a[j][q];
               a[q][j] = a[j][q];
               a[j][p] = h; a[p][j] = h;
          for (j=p+1;j<q;j++){
               h = c*a[p][j] - s*a[j][q];
               a[j][q] = s * a[p][j] + c*a[j][q];
               a[q][j] = a[j][q];
               a[p][j] = h; a[j][p] = h;
          for (j=q+1;j<n;j++){
               h = c*a[p][j] - s*a[q][j];
               a[q][j] = s*a[p][j]+c*a[q][j];
               a[j][q] = a[q][j];
               a[p][j] = h; a[j][p] = h;
     return h;
     private class WindowCloser extends WindowAdapter
          public void windowClosing(WindowEvent event)
               dispose();

Can somebody help me with this bit. I have got the problem down to this:
// Generate random values for the first matrix     
          for (i=0; i<n; i++)
               for (j=0; j<n; j++)
                    a[i][j] = Numeric.randomDouble(-100, 100);                    
          // Prints out the values in a table
          for (i=0; i<n; i++)
               for (j=0; j<n; j++)
                    a[i][j] = a[j];
                    table.setValueAt(""+a[i][j], i, j);
          // Calculation to find the max value in the matrix          
          max = 0;
          for (int i=0; i<n; i++)
               for (int j=i+1; j<n; j++)
                    if (Math.abs(a[i][j]) > (max))
                         max = Math.abs(a[i][j]);     
                         p=i; q=j;
          table.setValueAt("Matrix : "+x, (n-3),n);
          table.setValueAt("Row P : "+p, n-2,n);
          table.setValueAt("Column Q : "+q, n-1,n);
          table.setValueAt("Max value: "+max, n,n);
          /* Set the colour of the cells containing the max value
Now all I need to do is call a cell renderer and and colour the rows and columns that match p and q. If i get this, it would be a major load off my back. I have checked the forums and the only thing that I found close to this coloured each alternative ceill in.
As you can see from the previous note, my JTable is creatd all in one and i add the values to the bottom of it. I do not know if there is a way of dynamically appending tables to the botton of a scrollpane.
I am not the most experienced with java so it there is something slightly trickly in this, could you please explain it.
If any one can help it will be much appreciated.

Similar Messages

  • How  to set DataGrid one cell colour

    I want to set one cell colour in DataGrid,for example,when a
    set a CheckBox in DataGrid ,I want letset this Cell's colour
    change

    One way to work around this, might be to create your own
    cellrenderer with an extra backround movie clip. So as you pass the
    value of the check box, either you set the fill color of the BG
    movie clip or just hide/show the BG clip.
    I hope the following brief script might be of help,
    class myCell extends UIComponent
    var bg:MovieClip;
    var cBox:CheckBox;
    function createChildren(Void) : Void
    // Create a new CheckBox
    // Create a new Background Clip
    bg = this.createEmptyMovieClip("bg_mc" , 0);
    bg.beginFill(color, fill);
    bg.moveTo(0, 0);
    bg.lineTo(4, 0);
    bg.lineTo(4, 4);
    bg.lineTo(0, 4);
    bg.lineTo(0, 0);
    bg.endFill();
    size();
    function size(Void) : Void
    super.size();
    this["bg_mc"]._width = width;
    this["bg_mc"]._height = height;
    invalidate();
    function setValue(cellVal) : Void
    if (cellVal == true)
    bg._visible = true;
    else
    bg._visible = false;
    Notes: BG: is the background movie clip.
    You will need to use AS based cellrenderer

  • Tab between cells and Editor in JTable

    I placed a cell editor in a JTable column JTextField.
    After I type something in this editor and press tab it stays in the same cell and when I press tab again then it goes to the next column.
    How can I correct this so that after I type something in the cell and press tab I want it to go to the next column directly in JTable.
    Thanks.

    I'd have to see your code to tell you what's wrong. I tried it this way and had no problem.
    TableColumn tc = table.getColumnModel().getColumn(2);
    tc.setCellEditor(new DefaultCellEditor(new JTextField()));by the way, I don't think you need to explicitly set the cell editor component to JTextField. It uses that by default.

  • Tab between cells and celleditor in JTable

    I placed a cell editor in a JTable column JTextField.
    After I type something in this editor and press tab it stays in the same cell and when I press tab again then it goes to the next column.
    How can I correct this so that After I type something in the cell and press tab I want it to go to the next column directly in JTable.
    Thanks.

    I'd have to see your code to tell you what's wrong. I tried it this way and had no problem.
    TableColumn tc = table.getColumnModel().getColumn(2);
    tc.setCellEditor(new DefaultCellEditor(new JTextField()));by the way, I don't think you need to explicitly set the cell editor component to JTextField. It uses that by default.

  • ALV Cell colour

    Hi,
      I want to display the cell colour based on some condition in the ALV grid. pls help me in this.
    Regards
    Rajesh.V

    Hi,
    In Function Module REUSE_ALV_GRID_DISPLAY
    types: begin of slis_specialcol_alv,
    fieldname type slis_fieldname,
    color type slis_color,
    nokeycol(1) type c,
    end of slis_specialcol_alv.
    You can mention color for the display
    and .............
    *& Report ZDEMO_ALVGRID *
    *& Example of a simple ALV Grid Report *
    *& The basic ALV grid, Enhanced to display each row in a different *
    *& colour *
    REPORT zdemo_alvgrid .
    TABLES: ekko.
    type-pools: slis. "ALV Declarations
    *Data Declaration
    TYPES: BEGIN OF t_ekko,
    ebeln TYPE ekpo-ebeln,
    ebelp TYPE ekpo-ebelp,
    statu TYPE ekpo-statu,
    aedat TYPE ekpo-aedat,
    matnr TYPE ekpo-matnr,
    menge TYPE ekpo-menge,
    meins TYPE ekpo-meins,
    netpr TYPE ekpo-netpr,
    peinh TYPE ekpo-peinh,
    line_color(4) type c, "Used to store row color attributes
    END OF t_ekko.
    DATA: it_ekko TYPE STANDARD TABLE OF t_ekko INITIAL SIZE 0,
    wa_ekko TYPE t_ekko.
    *ALV data declarations
    data: fieldcatalog type slis_t_fieldcat_alv with header line,
    gd_tab_group type slis_t_sp_group_alv,
    gd_layout type slis_layout_alv,
    gd_repid like sy-repid.
    *Start-of-selection.
    START-OF-SELECTION.
    perform data_retrieval.
    perform build_fieldcatalog.
    perform build_layout.
    perform display_alv_report.
    *& Form BUILD_FIELDCATALOG
    Build Fieldcatalog for ALV Report
    form build_fieldcatalog.
    There are a number of ways to create a fieldcat.
    For the purpose of this example i will build the fieldcatalog manualy
    by populating the internal table fields individually and then
    appending the rows. This method can be the most time consuming but can
    also allow you more control of the final product.
    Beware though, you need to ensure that all fields required are
    populated. When using some of functionality available via ALV, such as
    total. You may need to provide more information than if you were
    simply displaying the result
    I.e. Field type may be required in-order for
    the 'TOTAL' function to work.
    fieldcatalog-fieldname = 'EBELN'.
    fieldcatalog-seltext_m = 'Purchase Order'.
    fieldcatalog-col_pos = 0.
    fieldcatalog-outputlen = 10.
    fieldcatalog-emphasize = 'X'.
    fieldcatalog-key = 'X'.
    fieldcatalog-do_sum = 'X'.
    fieldcatalog-no_zero = 'X'.
    append fieldcatalog to fieldcatalog.
    clear fieldcatalog.
    fieldcatalog-fieldname = 'EBELP'.
    fieldcatalog-seltext_m = 'PO Item'.
    fieldcatalog-col_pos = 1.
    append fieldcatalog to fieldcatalog.
    clear fieldcatalog.
    fieldcatalog-fieldname = 'STATU'.
    fieldcatalog-seltext_m = 'Status'.
    fieldcatalog-col_pos = 2.
    append fieldcatalog to fieldcatalog.
    clear fieldcatalog.
    fieldcatalog-fieldname = 'AEDAT'.
    fieldcatalog-seltext_m = 'Item change date'.
    fieldcatalog-col_pos = 3.
    append fieldcatalog to fieldcatalog.
    clear fieldcatalog.
    fieldcatalog-fieldname = 'MATNR'.
    fieldcatalog-seltext_m = 'Material Number'.
    fieldcatalog-col_pos = 4.
    append fieldcatalog to fieldcatalog.
    clear fieldcatalog.
    fieldcatalog-fieldname = 'MENGE'.
    fieldcatalog-seltext_m = 'PO quantity'.
    fieldcatalog-col_pos = 5.
    append fieldcatalog to fieldcatalog.
    clear fieldcatalog.
    fieldcatalog-fieldname = 'MEINS'.
    fieldcatalog-seltext_m = 'Order Unit'.
    fieldcatalog-col_pos = 6.
    append fieldcatalog to fieldcatalog.
    clear fieldcatalog.
    fieldcatalog-fieldname = 'NETPR'.
    fieldcatalog-seltext_m = 'Net Price'.
    fieldcatalog-col_pos = 7.
    fieldcatalog-outputlen = 15.
    fieldcatalog-datatype = 'CURR'.
    append fieldcatalog to fieldcatalog.
    clear fieldcatalog.
    fieldcatalog-fieldname = 'PEINH'.
    fieldcatalog-seltext_m = 'Price Unit'.
    fieldcatalog-col_pos = 8.
    append fieldcatalog to fieldcatalog.
    clear fieldcatalog.
    endform. " BUILD_FIELDCATALOG
    *& Form BUILD_LAYOUT
    Build layout for ALV grid report
    form build_layout.
    gd_layout-no_input = 'X'.
    gd_layout-colwidth_optimize = 'X'.
    gd_layout-totals_text = 'Totals'(201).
    Set layout field for row attributes(i.e. color)
    gd_layout-info_fieldname = 'LINE_COLOR'.
    gd_layout-totals_only = 'X'.
    gd_layout-f2code = 'DISP'. "Sets fcode for when double
    "click(press f2)
    gd_layout-zebra = 'X'.
    gd_layout-group_change_edit = 'X'.
    gd_layout-header_text = 'helllllo'.
    endform. " BUILD_LAYOUT
    *& Form DISPLAY_ALV_REPORT
    Display report using ALV grid
    form display_alv_report.
    gd_repid = sy-repid.
    call function 'REUSE_ALV_GRID_DISPLAY'
    exporting
    i_callback_program = gd_repid
    i_callback_top_of_page = 'TOP-OF-PAGE' "see FORM
    i_callback_user_command = 'USER_COMMAND'
    i_grid_title = outtext
    is_layout = gd_layout
    it_fieldcat = fieldcatalog[]
    it_special_groups = gd_tabgroup
    IT_EVENTS = GT_XEVENTS
    i_save = 'X'
    is_variant = z_template
    tables
    t_outtab = it_ekko
    exceptions
    program_error = 1
    others = 2.
    if sy-subrc 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    endif.
    endform. " DISPLAY_ALV_REPORT
    *& Form DATA_RETRIEVAL
    Retrieve data form EKPO table and populate itab it_ekko
    form data_retrieval.
    data: ld_color(1) type c.
    select ebeln ebelp statu aedat matnr menge meins netpr peinh
    up to 10 rows
    from ekpo
    into table it_ekko.
    *Populate field with color attributes
    loop at it_ekko into wa_ekko.
    Populate color variable with colour properties
    Char 1 = C (This is a color property)
    Char 2 = 3 (Color codes: 1 - 7)
    Char 3 = Intensified on/off ( 1 or 0 )
    Char 4 = Inverse display on/off ( 1 or 0 )
    i.e. wa_ekko-line_color = 'C410'
    ld_color = ld_color + 1.
    Only 7 colours so need to reset color value
    if ld_color = 8.
    ld_color = 1.
    endif.
    concatenate 'C' ld_color '10' into wa_ekko-line_color.
    wa_ekko-line_color = 'C410'.
    modify it_ekko from wa_ekko.
    endloop.
    endform. " DATA_RETRIEVAL
    Hope this Helps.
    Regards ,

  • Cell border removal in JTable

    I've created a JTable with a DefaultCellRenderer. I need a way of removing the border that appears around each cell(deafult yellow colour) and instead replace it with no border or a border that goes around the entire row. Any ideas?

    add this to your code, just after you create the table:UIManager.put("Table.focusCellHighlightBorder", BorderFactory.createEmptyBorder());

  • Remove Cell Selection Border in JTable

    Hi
    I have multiple columns in JTable populated with data. When the row is selected, the row changes colour. It also places a border around the cell that is selected within the row.
    Is there some way to remove this border?
    Any help would be appreciated.
    Thanks
    Gregg

    Hi,
    you need a different tableCellRenderer. Read:
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#custom
    There are also code examples.
    Phil

  • Planning book Cell colours are not displayed correctly in upgarded SCM 7.0

    Hi All
    WE have recently upgarded SCM 4.1 to SCM 7.0 system and I am testing new system. I am stuck in one issue . We have some keys figure rows which are open of inout/output. WE have macros for this key figures to close for certian period. After closing we defined cell Background colour to be same as default colour of other rows in planning book. For SCM 4.1 we used colour no 9 for this.
    But in New System SCM 7.0 looks like colour numbers have changed. So I changed macros for background colour , we have an option when changing system gives colour palett and we can select, I tested the whole pallett fo matching colour with default planning book celllc colours- no colour is matching , when I look at palett it looks same but when I  select that in macro the shade looks diferent . 
    Can some one advice how can we get exact colout number to match defult colour of palnning book cells.
    Thanks
    KV

    Hi Kristin,
    You can always change the cell color to default by using 0 as argument of the macro function. For instance, the following macro change the color of cell to red if the corresponding prop factor value is negative. On the other hand, for a positive value or zero, the default background color is retained.
    Thanks,
    Rajesh

  • How can i make perticular row or perticular cell Editable  of a JTable

    Dear al,
    can u help me by guiding me for the problem of...
    i am having a JTable, in which a (first)column of each row is having a checkbox field.
    If the checkbox is checked then and then i should able to modify the cells in that row where the checkbox is.
    I have created the table with AbstractTableModel of which the isCellEditable(int row, int col) method is overwriten. Whatever return value (true/false) reflects the perticular
    cells becomes editable/non-editable respectively.
    but at run time...(mean the table is created now) and now i want to make the cells editable/non-editable depending on the checkbox value...
    how can i implement it.........
    please suggest.........
    thank you.........

    here is the sample code from tutorial.......
    * TableRenderDemo.java requires no other files.
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    * TableRenderDemo is just like TableDemo, except that it explicitly initializes
    * column sizes and it uses a combo box as an editor for the Sport column.
    @SuppressWarnings("serial")
    public class TableRenderDemo extends JPanel {
         private boolean DEBUG = true;
         public TableRenderDemo() {
              super(new GridLayout(1, 0));
              JTable table = new JTable(new MyTableModel());
              // table.setEditingColumn(0);
              // table.editCellAt(0, 0);
              table.setPreferredScrollableViewportSize(new Dimension(500, 100));
              // Create the scroll pane and add the table to it.
              JScrollPane scrollPane = new JScrollPane(table);
              // Set up column sizes.
              initColumnSizes(table);
              // Fiddle with the Sport column's cell editors/renderers.
              setUpSportColumn(table, table.getColumnModel().getColumn(2));
              // Add the scroll pane to this panel.
              add(scrollPane);
          * This method picks good column sizes. If all column heads are wider than
          * the column's cells' contents, then you can just use
          * column.sizeWidthToFit().
         private void initColumnSizes(JTable table) {
              MyTableModel model = (MyTableModel) table.getModel();
              TableColumn column = null;
              Component comp = null;
              int headerWidth = 0;
              int cellWidth = 0;
              Object[] longValues = model.longValues;
              TableCellRenderer headerRenderer = table.getTableHeader()
                        .getDefaultRenderer();
              for (int i = 0; i < 5; i++) {
                   column = table.getColumnModel().getColumn(i);
                   comp = headerRenderer.getTableCellRendererComponent(null, column
                             .getHeaderValue(), false, false, 0, 0);
                   headerWidth = comp.getPreferredSize().width;
                   comp = table.getDefaultRenderer(model.getColumnClass(i))
                             .getTableCellRendererComponent(table, longValues, false,
                                       false, 0, i);
                   cellWidth = comp.getPreferredSize().width;
                   if (DEBUG) {
                        System.out.println("Initializing width of column " + i + ". "
                                  + "headerWidth = " + headerWidth + "; cellWidth = "
                                  + cellWidth);
                   // XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
                   column.setPreferredWidth(Math.max(headerWidth, cellWidth));
         public void setUpSportColumn(JTable table, TableColumn sportColumn) {
              // Set up the editor for the sport cells.
              JComboBox comboBox = new JComboBox();
              comboBox.addItem("Snowboarding");
              comboBox.addItem("Rowing");
              comboBox.addItem("Knitting");
              comboBox.addItem("Speed reading");
              comboBox.addItem("Pool");
              comboBox.addItem("None of the above");
              sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
              // Set up tool tips for the sport cells.
              DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for combo box");
              sportColumn.setCellRenderer(renderer);
         class MyTableModel extends AbstractTableModel {
              private String[] columnNames = { "First Name", "Last Name", "Sport",
                        "# of Years", "Vegetarian" };
              private Object[][] data = {
                        { "Mary", "Campione", "Snowboarding", new Integer(5),
                                  new Boolean(false) },
                        { "Alison", "Huml", "Rowing", new Integer(3), new Boolean(true) },
                        { "Kathy", "Walrath", "Knitting", new Integer(2),
                                  new Boolean(false) },
                        { "Sharon", "Zakhour", "Speed reading", new Integer(20),
                                  new Boolean(true) },
                        { "Philip", "Milne", "Pool", new Integer(10),
                                  new Boolean(false) } };
              public final Object[] longValues = { "Sharon", "Campione",
                        "None of the above", new Integer(20), Boolean.TRUE };
              public int getColumnCount() {
                   return columnNames.length;
              public int getRowCount() {
                   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 false;
                   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) {
                   if (DEBUG) {
                        System.out.println("Setting value at " + row + "," + col
                                  + " to " + value + " (an instance of "
                                  + value.getClass() + ")");
                   data[row][col] = value;
                   fireTableCellUpdated(row, col);
                   if (DEBUG) {
                        System.out.println("New value of data:");
                        printDebugData();
              private void printDebugData() {
                   int numRows = getRowCount();
                   int numCols = getColumnCount();
                   for (int i = 0; i < numRows; i++) {
                        System.out.print(" row " + i + ":");
                        for (int j = 0; j < numCols; j++) {
                             System.out.print(" " + data[i][j]);
                        System.out.println();
                   System.out.println("--------------------------");
         * Create the GUI and show it. For thread safety, this method should be
         * invoked from the event-dispatching thread.
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame("TableRenderDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Create and set up the content pane.
              TableRenderDemo newContentPane = new TableRenderDemo();
              newContentPane.setOpaque(true); // content panes must be opaque
              frame.setContentPane(newContentPane);
              // Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args) {
              // Schedule a job for the event-dispatching thread:
              // creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();

  • How to catch change cell selection in a JTable?

    I'm using a ListSelectionListener with a JTable to catch the list selection changes but it only detects row changes, and if i select a different cell but within the same row it does not trigger the event.
    Do you guys know a way to detect this event?
    Thanks!!!

    I'm using a ListSelectionListener with a JTable to catch the list selection changes but it only detects row changes,Try adding a listener for the columns as well:
    table.getTableHeader().getColumnModel().getSelectionModel().addListSelectionListener(...);

  • Custom table cell renderer in a JTable is not called

    Hello, all,
    I have the following task: I need to select several cells in a column, change the value of those cells, and once the value changes, the color of these cells should change as well. I wrote a custom cell renderer, and registered it for the object type that will use it to render the cell. However, the custom cell renderer is never called. Instead, the class name of the object is displayed in the cell.
    My code snippents are as follows:
    //Declare the table and add custom cell renderer
    JTable table = new JTable (7,7);
    table.setCellSelectionEnabled (true);
    table.setSelectionMode (ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    //Add the custom cell renderer to render objects of type Item
    table.setDefaultRenderer(Item.class, new CustomTableCellRenderer());
    //Get the selected cells and change the object type in those cells
    //This part works, since I see the app entering the for loop in the debugger, and the item.toString() value is displayed in each selected cell
    int rowIndexStart = table.getSelectedRow();
    int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
    int colIndex = table.getSelectedColumn();
    Item item = new Item ();
    for (int i = rowIndexStart; i<=rowIndexEnd; i++){
                  table.setValueAt(item, i, colIndex);
                 //I expect the cell to redraw now using custom cell renderer defined below, but that cell render is never called.  Instead, the item.toString() value is displayed in the cell.   What is wrong?
    //Definition of custom cell renderer. 
    //the getTableCellRendererComponent is never called, since the System.out.println never prints.  I expected this method to be called as soon as the Item object is added to the cell.  Am I wrong in expecting that?
    class CustomTableCellRenderer extends DefaultTableCellRenderer  {
        public Component getTableCellRendererComponent (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component cell = super.getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column);
            System.out.println("value: "+value.getClass()+" isSelected "+isSelected+" hasFocus "+hasFocus+" row "+row+" col "+column);
            if (this.isFocusOwner()) {
            cell.setBackground( Color.red );
            cell.setForeground( Color.white );
            return cell;
    } Please, help,
    Thank you!
    Elana

    The suggestion given above assumes that all the data in a given column is of the same type.
    If you have different types of data in different rows the you should be overriding the getCellRenderer(...) method. Something like:
    public TableCellRenderer getCellRenderer(int row, int column)
        Object o = getValueAt(row, column);
        if (o instanceof Item)
            return yourCustomRenderer
        else
            return super.getCellRenderer(row, column);
    }

  • Cell L&F of JTable

    hi ,
    I have a JTable contructed from DeaultTableModel and
    i have created a TableCellEditor which has a custom DefaultCellRenderer as its argument and
    added to the table
    THE PROBLEM is :
    When i edit in the table cell , the editable area of the cell becomes smaller compared to the area without a TableCellEditor, how can i change it ?
    and i want to change the border of the celll which is selected and its color
    Any Help ? Please.
    thanks.

    From one of the MS windows books.....Going by the books, eh?
    Well, apparently MS doesn't do so with Excel... Pressing space will simply trigger an edit!
    q1) JTable should have space bar handling out of the box?
    (space, CTRL+space, shift+space)
    I have not seen this raised as a bug.A bug, no... a feature, maybe. Anyway, JTable provides most of the features needed for creating a table -- it's far from perfect..... adding support for CTRL+SPACE and SHIFT+SPACE is not all that hard to do.
    q2) Should the enter key put an editable cell under edit and
    q3) if not should the first enter key stop cell editing and a second press activate the default buttonIMHO, a good answer to your question can be found by running MS Excel and see how it's done.
    The escape key will cancel editing of a cell that is under edit.and q4, q5
    It should, as in Excel. But then, in Lotus 1-2-3, first escape will clear the edit buffer (unless it's empty) and the second escape will cancel editing. Who'is more programmatically correct (I don't know)?
    ;o)
    V.V.

  • Change cell's color in jtable when user clicks on it

    Hi everyone,
    i've got a JTable, and would like to change the background of a cell when user selects it
    so i added a mouselistener over my jtable, the mousereleased method looks like this:
              public void mouseReleased(MouseEvent e) {
                   int row = table.rowAtPoint(e.getPoint());
                   int column = table.columnAtPoint(e.getPoint());
                            // help needed
              }as you see, i found the code to get the index of the cell selected, but i don't find any method in JTable class to get the cell component itself, and to alter its background color
    Please notice that the "setSelectionBackground()" in JTable isn't enough, since i would also like to change the color of cells which are not selected when the user select a cell
    how could i do that?
    Thanks in advance!
    edit: i tried the following but it does not work either
              public void mouseReleased(MouseEvent e) {
                   int row = table.rowAtPoint(e.getPoint());
                   int column = table.columnAtPoint(e.getPoint());
                   AbstractTableModel atm = (AbstractTableModel) table.getModel();
                   Component cell = table.getDefaultRenderer(CaseMemoire.class).
                   getTableCellRendererComponent(table, atm.getValueAt(row, column), true, true, row, column);
                   cell.setBackground(Color.MAGENTA);
                   table.updateUI();
              }

    ok i found how to do it
    i directly inserted this in the renderer code:
    if (row == table.getSelectedRow() && column == table.getSelectedColumn())
    cell.setBackground(etc);
    (curiously it does not work with "if (isSelected)")
    thanks :)

  • First cell not selected in JTable

    When selecting multiple cells in JTable by pressing the mousebutton and draging the selection over the cells you want to select the first cell is not selected (it stays white).
    Any suggestions on how to fix this?

    I am running in M$ Windows.
    The first cell (anywhere in the Table) when you press the mouse to select a range of cells is present by color white (depend on L&F setting).
    The white color on first cell does not means the first cell is not selected!!!
    ( The first cell is selected, but present by white color to show you that is the start point )
    (if you use M$ Excel, that is the same effect presentation! )
    Hope this helps.

  • Focus cell editor component of JTable when starting editing by typing

    Hello, everybody.
    We all know that the JTable component doesn't actually focus the actual cell editor component when editing is started by typing. But I need this functionality in an application of mine. So, I ask: is there a way to transfer focus to the editor component when editing is started by typing?
    Thank you.
    Marcos

    Well, I think that I've found it: JTable#setSurrendersFocusOnKeystroke.
    Marcos

Maybe you are looking for