Setting the backgroundcolor of cell of JTable

Hi
My Problem is.
I have a JTable with 2 columns ( Rows can be 1-10 depending upon the size of
input vector)
I have provided two button in my Frame
1)Update Row
2) Update whole Table.
Now i want I want that if a user makes a change in any cell say cell( row
3,Col 1) ;and moves to next row , then the color (background/foreground) of
that cell should change to any other color .Again if he presses any of the
button then the default color of the cell should be restored.Basically i
want to indicate the user that he has made changes in the cell and he needs
to press the button for updation
Regards
Aminur

You need to write your own TableCellRenderer if you want to control how individual table cells appear. Look in the How to Use Table tutorial if you haven't already done that; you'll find a link to it in the API documentation for the JTable class. And in that renderer, if you use a JLabel to render the cell, remember that a JLabel defaults to being transparent, i.e. you can't see its background. Use "setOpaque(true)" if you want to control the background colour.

Similar Messages

  • How do I set background color of cell using JTable?

    Hello all!
    I have a question on the use of JTables. I am using a JDialog consisting of a JTable and a number of buttons to insert and to select OK or cancel. Everything is working perfectly, but I now must add editing capabilities to prevent invalid data being used in a SQL query to update or insert rows.
    So far I can't figure out how to get at a cell to set the background to red if the user inputs a Date incorrectly. Upon setValueAt(), I take this value and check for standard format errors. I hope to someday convert the column altogether to a Data object (or some form since Date is deprecated):-) For the time being, I know when an error occurs, but don't have the foggiest idea how to render the error (set backround to red).
    I need to give you more info too, since the way we do things is to make it as complicated as possible for job security and to impress the newbies(or scare them back to COBOL). When I setValueAt(), I have a DefaultDataElement object that houses everything for a given column in DB2. It has column name, length, data type, is it new, original value, current value, etc. If one doesn't exist, then I create one. After all said and done, I parse thru these elements and build my update/insert query and then execute the query.
    The event starts as soon as the user presses the OK button. But, if a date cell contains an invalid date, I need to halt processing (which I've done) and somehow let the user know which cell was invalid. We consider our users dumb (they really aren't, but the assumption is made), so I can't just say "error occurred in table. Verify data and try again". That won't work:-) Gotta be able to show them what cell is bad.
    Any ideas?
    Thanks,
    Patrick

    I finally figured it out. I was always close, but it wasn't until late yesterday that the light bulb came on. I was setting the background on the component in getTableCellEditorComponent() by grabbing the super.getTableCellEditorComponent(). The problem was all this was located in an editor, not renderer. So what happened was as I edited the cell the check would be performed then, not as focus was lost. When focus was lost, the red background went back to normal.
    I ripped the code out and made a custom renderer and got closer. Problem was the whole column had a red background. Even specifying the row and column in getTableCellRendererComponent didn't apply just to that cell. That row and column is only for obtaining the data in the cell, but anything affecting the component will affect the column, since I added the renderer to my TableColumn:-) I need to add error logic to my model and when an error occurs, set a boolean flag in a 2 dimensional array where the row and column is used to get to it from the renderer.
    Thanks for the help!!!

  • How to set the row height in a JTable

    Is there a way to set the height of a row (actually all rows) in a JTable?
    I have tried setting the font to be bigger but then the cells are not big enough.

    Use "rowHeight" method of JTable class.
    For more information about JTable class, please read the API documentation at http://java.sun.com/j2se/1.3/docs/api/javax/swing/JTable.html
    /Sreenivasa Kumar Majji.
    Is there a way to set the height of a row (actually
    all rows) in a JTable?
    I have tried setting the font to be bigger but then
    the cells are not big enough.

  • Set color of specific cells in JTable.

    I have a JTable where I want to set the color for specific cells. Is this possible to do, and if so, how?

    Well, one way is to create a custom renderer that know the background color of each cell in the table. The Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#renderer]How to Use Table has an example you might be able to build on.
    Or, this posting may give you another approach. The key to both solutions is to somehow specify the color for every cell:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=610474

  • How can I set the af:table cell spacing ????

    Hi,
    I am using the af:table component and I need absolutely to set the cell spacing. I am afraid that it couldn't be possible.
    If you have any idea please dont hesitate.
    Many thanks

    Please lell me how can i create a TableModel , means
    we have to create a seperate class or I have to do
    like this---------------
    private TableModel myData;
    private JTable oTable = new JTable(myData);
    and call this method on table object
    int iRows = oTable.getRowCount();
    oTable.isCellEditable(iRows,2);\Something like this:
    public class MyTableModel extends DefaultTableModel {
        public boolean isCellEditable(int row, int col) {
            return false;
    }Or even better, extend AbstractTableModel. AbstractTableModel already overrides isCellEditable to return false.
    public class MyTableModel extends AbstractTableModel {
    }Graeme

  • Set the name of cell or cells' range for a report and when export it to excel the names will be defined.

    Hello,
    I have an C# application that exports report from Reporting Services to Excel files.
    I would like to know if there is a possibility to set the name of the cell or range of cells in the report (via Report Builder or somewhere else) and when open the Excel the names are set. Similar functinality when you open the Excel and go Formulas/Define
    Name and set the name for a unique cell or range.
    Regards,

    Hi there,
    I don't believe this is possible in Reporting Services.  One workaround, if you don't know the exact range at runtime, might be to put hidden characters (white?) in your sheet at start and end of range, then do some postprocessing on the file using
    VSTO or perhaps a 3rd-party tool like this one.  
    http://www.aspose.com/reporting-services/excel-component.aspx
    If you do know the range it should be much easier.
    cheers,
    Andrew
    Andrew Sears, T4G Limited, http://www.performancepointing.com

  • How to set the border of header of JTable

    I am using the following code to set the border of my JTable headers but it doesn't seem to work!! The headers do get CENTER aligned but somehow they do not show the right border. Please Help.
    class cellAlignRenderer extends DefaultTableCellRenderer
    cellAlignRenderer()
    setHorizontalAlignment(JLabel.CENTER);
    Border b = BorderFactory.createEtchedBorder() ;
    setBorder(b);
    jTable.getColumn(0).setHeaderRenderer( new cellAlignRenderer());

    try this
    public class YourTableHeaderRenderer extends DefaultTableCellRenderer
    public YourTableHeaderRenderer()
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column)
    JLabel comp = (JLabel) super.getTableCellRendererComponent(table,value,
    isSelected,hasFocus,row,column);
    try
    comp.setBorder(BorderFactory.createBevelBorder(0,Color.lightGray,Color.darkGray));
    setFont(new java.awt.Font("Dialog", 0, 15));
    setHorizontalAlignment(SwingConstants.CENTER);
    catch(Exception err)
    err.printStackTrace();
    return this;

  • How to control the input in cell of Jtable must be number?

    I want to control the character of cell or column of jtable, it must be number(0-9),
    only the user type number(0-9) will show on the jtable.
    how can i do that, can you give me a little example or hints?
    Thanks very much!

    Hi,
    Your question is not that clear to me but... I believe that putting a PlainDocument class on the JTextField of the JTableCellEditor and overriding the insertString method would do the trick...
    JRG

  • How to set the default Excel cell format when opening XML to XLS using an existing stylesheet​?

    Hi,
    I have an XML file, which I'm opening with the Excel application. The stylesheet I use is horizontal.xsl.
    The problem arised when the XML has data in the format "1/4" or "1/16", which is translated in the Excel as date (like "01/04/2007").
    I think I have to set the default cell type to "Text" instead of "General". Does anyone know how it can be done?

    Is this the same question as idoZo, if so jigg has already answered it. If not then you should post your own query not hijack someone elses giving a clear and concise question, "how to set it??" doesn't help you or other in the forum to provide you with a solution.
    Is this relevant to TestStand? If it is then help by providing which version you are using and what software you are using with it. If not then post your question in the correct board.
    Regards
    Ray Farmer

  • Setting the excel sheet cell category

    Hi all,
    I have a program which downloads SAP data in excel sheet using OLE (Function modules cannot be used as its multiple tab download).
    I am facing an issue regarding the date fields.The cell category (data type) is choosen randomly so the date is displayed in wrong format.So  i need to set the category or the data type of the cell before populating the data in it.
    I have placed a part of my code below.
    CALL METHOD OF gw_sheet 'cells' = gw_cells
            EXPORTING
            #1 = g_row
            #2 = g_col.
          SET PROPERTY OF gw_cells 'value' = lw_table-data.
    Can somebody help me in setting the data type of the cell ( eg,Number,text,date,Currency etc)
    Ps :- Actually i need to set the data type as Text for all cells.
    Thanks in advance,
    Kiran

    Try like:
    CALL METHOD OF gw_sheet 'cells' = gw_cells
    EXPORTING
    #1 = g_row
    #2 = g_col.
    SET PROPERTY OF gw_cells 'NumberFormat' = '@'.   "For Text
    To get the Property in excel you can take a help of Macro.
    Follow this steps:
    1. Create a new workbook
    2. Tools > Macro > Record a new macro
    3. Now, perform your actions i.e. Set the cell format to Text
    4. Stop the Macro Tools > Macro > Stop Recording
    5. Now Edit Macro to see which property it has accessed.
    Tools > Macro > Run (Alt + F8)
    Select Your macro and Edit
    Here you will see which property you have to set to make it Text.
    Regards,
    Naimesh Patel

  • HELP Friends!!! How to set the width of columns of JTABLE?

    Hi!
    How to set the width of a particular column in JTable?
    I tried using headerRenderers and though I'm able to set the color and font of the header (using getTableCellRendererComponent method)I can't change the size.
    Pls some one help me..it's very urgent.
    Thanks in advance.
    Regards,
    Naval

    JTable.getColumnModel().getColumn(i).setWidth(width). There are also setPreferredWidth, setMaxWidth and setMinWidth methods.

  • Setting value in a cell in JTable where editor for cell is a JComboBox

    Hi,
    I have a column in a JTable where it holds a comboBox . As the comboBox has different
    values depending on the row I've a cell editor for each row. That's fine. My problem is that one of the
    values on the comboBox launches a dialog where the user selects a new value to add to the comboBox.
    The comboBox gets updated with this new value and I call setValueAt on the table. Both get updated
    but the cell doesn't display the new value added in the JTable. I click it and the comboBox has the
    value and I've to select it to get it displayed in the cell.
    Here's the code for updating the tableModel -
    public void updateCellDetails(String value, int row)
    JComboBox combo = (JComboBox) rowEditor.getTableCellEditorComponent(
                        this,
                        value,
                        true,
                        row,
                        4);
    if (combo != null)
    combo.insertItemAt(value, combo.getItemCount() - 1);
    combo.setSelectedItem(value);
    rowEditor.setEditorAt(row, new DefaultCellEditor(combo));
    MyTableModel tableModel = (MyTableModel) getModel();
    tableModel.setValueAt(value, row, 4);
    Thanks

    Not sure if this'll help, but did you ever fire an editing-stopped event? If such an event is never fired, then editing-cancelled will be fired when you lose focus from the editor and the original value will be restored.

  • How to set the width of a cell in JTable?

    I have created a JTable and I want to set the width of cells.How can I do that?

    This is now the third person to tell you that Swing questions should be posted in the Swing forum.
    You have several postings out there where you have been given an answer but you haven't bothered to respond to the posting. Indicating whether the suggestion was helpfull or not. I guess you really don't want help from people in the future.

  • Writing own TableCellRenderer for setting the Background Color of a cell ?

    Hello,
    I am using the JTable and DefaultTableModel for my GUI. I use also only plain text in the rows and columns. I have a method which examine every row wether something is wrong with a string so if something is wrong i want to set the BackgroundColor of this cell with the bad string to a color i can define.
    Do I need to write an own TableCellRenderer for this tiny task?
    Table class has no setBackground(new Color(22,22,22),posRow,posCol);

    http://forum.java.sun.com/thread.jspa?forumID=57&threa
    dID=606504this code is from your ColorRenderer class:
    public void actionPerformed(ActionEvent e)
                   Iterator it = colors.keySet().iterator();
                   while ( it.hasNext() )
                        Point key = (Point)it.next();
                        int row = key.x;
                        int column = key.y;
                        if (column == -1)
                             model.fireTableRowsUpdated(row, row);
                        else if (row == -1)
                             int rows = table.getRowCount();
                             for (int i = 0; i < rows; i++)
                                  model.fireTableCellUpdated(i, column);                              
              }you have set an ActionListener to the ColorRenderer class and put the actionPerformed method in it but compared to a JButton the actionPerformed method is called when i click the JButton but what you do in your code that the actionPerformed method is executed. I have deleted the whole actionPerformed method and the listener and still the cell is displayed with a color so was it for the blinking?
    And the method setBackground is nowhere called or run actively so is this method called internally by the ColorRenderer class? or is this method somehow called recursively as in the method setBackground I can see this method call:
    c.setBackground( (Color)o ); but i think this is another setBackground method right? because the first method i mentioned has 3 parameters not 1 parameter so where is the method setBackground with 3 parameters called actively in your code? i cant find anything. ok after examining again the c.setBackground( (Color)o ); is the one with 3 parameters ;-)
    public void setBackground(Component c, int row, int column)
              { that was set for the previous cell, so reset it here
                   if (c instanceof DefaultTableCellRenderer)
                        c.setBackground( table.getBackground() );
                   //  In case columns have been reordered, convert the column number
                   column = table.convertColumnIndexToModel(column);
                   //  Get cell color
                   Object key = getKey(row, column);
                   Object o = colors.get( key );
                   if (o != null)
                        c.setBackground( (Color)o );
                        return;
                   //  Get row color
                   key = getKey(row, -1);
                   o = colors.get( key );
                   if (o != null)
                        c.setBackground( (Color)o );
                        return;
                   //  Get column color
                   key = getKey(-1, column);
                   o = colors.get( key );
                   if (o != null)
                        c.setBackground( (Color)o );
                        return;
              }using your full code gives me a bug:
    when i double click in the first column to change some text doesnt matter which row then the selected cell gets a red border and the rest of the table freezes. When i exchange the order of the columns move column 1 to 2 and column 2 to 1 then the freezed table is working again?? could you help solving that problem else the cell color setting works fine for me :-) thank you very much!

  • JTable Model   --  How to set the width of columns

    Hello,
    This project of mine is due in 2 days. :(
    I am using AbstractTableModel and I can't figure out how to set the columns' width inside my JTable?
    This following code does not work.
    int vColIndex = 1;
    TableColumn col = table.getColumnModel().getColumn(vColIndex);
    int width=399;
    col.setPreferredWidth(width);Please remember, that I'm using AbstractTableModel and not just simple JTables.
    Thanks in advance.

    The DataModel (AbstractTableModel or otherwise) has nothing to do with the table column size. The DataModel is used to store data.
    When you create a JTable using a DataModel then a TableColumn is created for each column in the DataModel using a default column size. The normal order of creation would be:
    TableModel model = new DefaultTableModel(...);
    JTable table = new JTable(model);
    Now that the table and table columns are created you can change the size of the columns:
    int vColIndex = 1;
    TableColumn col = table.getColumnModel().getColumn(vColIndex);
    int width=399;
    col.setPreferredWidth(width);
    So your code looks ok.
    However, if somewhere in you code you do:
    a) table.setModel(...)
    b) fireTableStructureChanged();
    then the table columns are recreated based on the current DataModel and the table column size would be reset to the default values.

Maybe you are looking for

  • PC/TV HDMI connection for both sound and vision

    I want to connect to my TV with a HDMI cable. I understand that I must install a SPDIF cable from my graphics card to my motherboard. I have found the card connection but where is the motherboard one? I have a Compac presario Product No. SR1230UK

  • Oracle Business Intelligence with big data

    Has anyone implemented OBIEE 10g utilizing a denormalized data model for a very large transactional data set? There is a potential to generate reports in the 100s of millions of rows, with the data warehouse storing fact tables that have ~1.5 billion

  • IOS 8 in compatible with iPad 2

    Ios8 and ipad2 are not compatible.  Why was this down load allowed?  I feel like I'm a heart beat from a total crash. Have reset and reloaded. No improvement.  Have deleted all games. No improvement.  I have 9 gigs of available memory, but have majoy

  • Reinstalling Photoshop Elements 11

    My computer went on the fritz and I uninstalled Photoshop Elements 11 to start over clean.   Now I am trying to REINSTALL and it is asking for S/N -- which originally I had to go through quite a process to get the first time.   I do not know what the

  • 4507-E LineCards Throughput Division. (URGENT)

    My Company has bought a Modular 4507-E to be implemented in Our Backbone, the Line Cards are as Follows: WS-X4248-FE-SFP    Catalyst 4500 48PT 100Base-X WS-C4507R+E           Catalyst 4500E 7 Slot chassis for 48Gbps/slot WS-X4640-CSFP-E    Catalyst 4