Alternating row backgrounds on a JTable

Howdy Partners,
I'm tryin' to get some examples of code that'll write a JTable with alternating background colour in the rows.
I need more than a couple of hints in a direction as I'm pretty green still. I've spent half the morning searching but can't find anything satisfactory.
Muchos gracias amigos.

Here is how you can do it.
import java.awt.Color;
import java.awt.Component;
import java.awt.event.MouseEvent;
import java.util.EventObject;
import javax.swing.DefaultCellEditor;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
public class Temp extends JFrame {
     private JTable table = null;
     private TableModel model = null;
     public Temp() {
          super("Test");
          setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
          model = new AbstractTableModel() {
               public int getColumnCount() {
                    return 3;
               public int getRowCount() {
                    return 30;
               public Object getValueAt(int rowIndex, int columnIndex) {
                    return "CELL " + ((rowIndex + 1) * (columnIndex + 1));
               public boolean isCellEditable(int row, int col) {
                    return true;
          table = new JTable(model);
          table.setDefaultRenderer(Object.class, new MyTableCellRenderer());
          JScrollPane scroller = new JScrollPane(table);
          getContentPane().add(scroller);
          pack();
          setVisible(true);
     public static void main(String [] args) throws Exception {
          new Temp();
     class MyTableCellRenderer extends JLabel implements TableCellRenderer {
          public MyTableCellRenderer() {
               super();
               setOpaque(true);
          public Component getTableCellRendererComponent(JTable table,
               Object value, boolean isSelected, boolean hasFocus,
               int row, int column) {
               setText(String.valueOf(value));
               Color bgColor = Color.white;
               if(row % 2 == 0) {
                    bgColor = Color.lightGray;
               setBackground(isSelected ? Color.blue : bgColor);
               setForeground(isSelected ? Color.white : Color.black);
               setFont(table.getFont());
               return this;
}Sai Pullabhotla

Similar Messages

  • How to draw Alternative Row Background in TileList?

    HI All,
    I have tried to draw Alternative Row Background by using drawRowBackground().
    But there is not parameter to pass the value.
    How to draw alternative row background in tilelist?

    Does Rado's following blog entry help: http://adf-rk.blogspot.com/2007/01/adf-oracle-form-like-overflow-in-adf.html

  • JTable row background change - based on EXTERNAL event

    Greetings folks!
    I'm hoping for some help with a JTable issue. Here's the scenario:
    The app is a point of sale application. The user scans or manually adds an item to the order, which causes a row to appear in the JTable displaying description, price, quantity, etc. The user can then right click a row on the JTable and select an option from the popup menu. If the user selects one of the options, I want to be able to change the background color on that row.
    EVERYTHING I've seen online and researching is based on adding a custom renderer to the jtable which changes the background based on the data in the row. In my case there isn't anything in the row which changes... hence the point of changing the color.
    What I'm looking for is a method which will let me change the background of row x. I'm guessing there isn't a way. I'm hoping someone has a suggestion.
    Thanks in advance,
    John E.
    PS: I'm fairly new to java and working with inherited code, so please no 'you need to redesign the world' type answers unless there's an easier way. :)

    In my case there isn't anything in the row which changesThen how is the table going to know what color to paint the row? Remember painting the row is a dynamic process. You can't just paint it once. You need the ability to repaint the row if for example the table is scrolled and the row is now longer present. Then when the table scrolls again and the row is present you need to be able to repaint the row in your specified color. This means you need some way to tell the table what color the row should be. Which means you need to keep that information somewhere.
    One way to do this is to store the data in the TableModel that indicates that this row should be painted a "different" color. Then your situation is like the examples you have found. You now have some data you can test. This column does not need to be visible in the table since you can remove the TableColumn from the TableColumnModel so the column is not painted.
    Here is a simple posting that shows a better approach to painting row backgrounds withouth using a renderer:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=610474

  • Change background color of alternating rows in listview

    Hi all,
    Does anyone know how to change the background color of alternating rows in a listview in Visual Basic 2013?
    Best regards,
    Randy Boulter

    You can set the OwnerDraw property of the ListView to true and use the DrawItem event:
    Private Sub ListView1_DrawItem(sender As Object, e As DrawListViewItemEventArgs) Handles ListView1.DrawItem
    e.DrawDefault = True
    If (e.ItemIndex Mod 2) = 1 Then
    e.Item.BackColor = Color.FromArgb(220, 220, 220)
    e.Item.UseItemStyleForSubItems = True
    End If
    End Sub

  • Can't get alternating rows style to work

    I have a spreadsheet in Numbers for iPad that I'm trying to style with alternating row colors. I don't even really care if its just gray and white, but I would like any form of alternating shades since I have a ton of data in one spreadsheet. It seems that no matter what I do on the settings, though, I can't get it to work. I tried changing the background of all the cells to no fill, then to white, then to gray...none of that seemed to make any difference. I also tried to select one of the pre existing styles and tried to apply that to my table and that also didn't seem to work. If anyone out there has any suggestions I would really appreciate it.
    Thanks

    Password for what?

  • Alternating row color for CF report Builder?

    I have a user who wants one of her reports to display
    alternating row colors for better read clarity. The reports are
    rather lengthy and the rows tend to blend in with eachother.

    Thanks Epulfy. I am going to give this a try later today.
    Much appreciated
    EDIT:: This does work. however I'm not sure how to set a
    rectangle to the background of the report so it's behind my
    details. I draw the rectangle and it just hides whatever I want to
    display. When I look at the report it does alternate with rows, but
    I can only see details from the rows that it does not alternate on.
    Any clue how to set it to the background?

  • Problem in setting the background color of jtable with Nimbus

    Hi
    I have created a java swing application. In which I am using JTable.
    When creating a simple JTable and displaying with Nimbus, the row background color alternates between white and a light blue-grey.
    I want the table with single colour. Only the first column should be grey colour and other should be white.
    I used this code to set the background and foreground colour.
    public Component prepareRenderer
        (TableCellRenderer renderer, int index_row, int index_col){      
                Component objComponent = super.prepareRenderer(renderer, index_row, index_col);         
                Color objGreyColour = new Color(240,240,240);
                Color objWhiteColour = new Color(255,255,255);
                if(index_col == 0){
                    objComponent.setBackground(objGreyColour);
                    objComponent.setFont(new java.awt.Font(CommonClass.getFontName(),java.awt.Font.BOLD, CommonClass.getFontSize()));
                    objComponent.setForeground(Color.BLACK);
                }else{               
                    setSelectionBackground(Color.BLUE);
                    objComponent.setBackground(objWhiteColour);
                    objComponent.setForeground(Color.BLACK);
                return objComponent;
            } Look wise it is fine but when i try to select the cell it is not highlighting the cell and also i m not able to select multiple cell with ctrl key.
    Any help would be appreciated
    Thanks
    Sonal

    Hello,
    1) if you want better help soone,r please post an SSCCE (http://sscce.org) instead of a code extract.
    2) selection highlighting is lost because your code... doesn't handle selection. To take selection into account, you can use <tt>if (super.isRowselected(index_row)) {...}</TT>.
    Regards,
    J.

  • Multiple alternating row colours

    I need to flag each row with different colours depending on the values in the columns. I believe you can do it in the definition of an alternating row report template but it only has entries for 4 conditions. How can I colour rows with more that 4 different colours at once? I have up to 8 possible conditions therefore I need up to 8 different colours displayed at once.
    regards
    Paul Platt

    Marc:
    I am not referring to the number of colors or the aesthetics. Just the difference in the visual appearance between
    http://htmldb.oracle.com/pls/otn/f?p=24317:55
    which uses the builtin Alternating Row Colors template
    vs what you suggested.
    In other words, the Alternating Row Colors template colors the row background but preserves the "grid" lines. Your solution obliterates all other styles on the row.
    Dont get me wrong, your solution is brilliant, very creative.
    On a related note, the technique I came up with, wrapping the entire row in a DIV and styling that in the query, doesnt work because it generates HTML like
    open TD1
    open DIV
    close TD1
    open TD2
    close DIV
    close TD2
    This messes up the DIV since it spans the TD cells.
    If it were to generate
    open DIV
    open TD1
    close TD1
    open TD2
    close TD2
    close DIV
    then my solution would work as well.
    But I dont think there is a way to generate a outer-most DIV like that using a column template, right? I cant modify the report template since my DIVs are going to contain dynamic styles from my query itself.
    Thanks

  • WAD - Portal - Changing row background colors

    Hi,
    We are creating web templates and posting to portal 6.0. I would like to know how to change the background colors for the rows for the output of the analysis item. Right now the default colors are grey and white (alternating rows). I did a search in the forum and it appears that there is no straightforward way to do it, with some suggesting we do it directly in the portal. Can someone provide detailed step by step instructions on how to change the background colors for rows for query output.
    Thanks,
    Anita S.

    You can modify the CSS (Cascading Style Sheet) in either Portal or WAD.  If you change it in Portal, it will be global for all reports viewed in the portal.
    For WAD, there is a general template parameter which contains the path to the .CSS file.  This CSS file is located in the Mime Repository (SE80).  Make the change to the css file in the mime repository and you're good to go.
    If you change the Portal CSS file, there is a wizard that can help you define colors for tables and preview them.

  • Interactive report default has alternating row colors, how to remove this?

    Is it possible to remove the alternating row colors from the interactive report.
    In a standard report I can select the report template, but in a interactive report not.
    Regards,
    Rob

    To customize a single page, add this rule to the CSS Inline page attribute:
    .apexir_WORKSHEET_DATA tr.odd td {
      background: rgb(242, 242, 242) !important;
    To apply to a complete application, either add
    .apexir_WORKSHEET_DATA tr.odd td {
      background: rgb(242, 242, 242) !important;
    to the Cascading Style Sheet Inline attribute on each page template, or create a CSS file containing
    .apexir_WORKSHEET_DATA tr.odd td {
      background: rgb(242, 242, 242);
    upload it to your workspace, and reference it after the theme link in each page template Header:
    <link rel="stylesheet" href="#IMAGE_PREFIX#themes/theme_4/css/theme_4_0.css" type="text/css" />
    <link rel="stylesheet" href="#WORKSPACE_IMAGES#theme_4_0_no_alt_row.css" type="text/css" />

  • Alternating Row Colors - Interactive Report

    Hello All,
    I'm hoping someone out there can help me out w/this. :)
    I'm a newbie working w/an Interactive Report and want to have alternating row colors as a default w/out losing the IR advantages.
    I've tried javascript, but, whenever filters are applied the class gets stripped off.
    Has anyone had any luck w/this?
    Thanks In Advance

    Roel,
    I got it working... Adding the onload to the image is pretty awesome, I had to chuckle cause I would've never thought of that.
    It wasn't working for me earlier, but, i realized after it was a silly syntax error. :P
    Anywho - Check the link below.
    http://apex.oracle.com/pls/otn/f?p=17445:7::::::
    I had used a different striping script which was written by a buddy of mine Keith Daulton (Had to throw him props for a hawt script. Works in ie6/7, FF, Chrome & Safari).
    I'm 100% sure I'm not the only one who's wanted this done and struggled to get it. So below I'm providing it for those who run into this thread.
    <script type="text/javascript">
    // THIS DOES THE STRIPING
    function decorateDataGrids (strClass) {
         var tables = document.getElementsByTagName("table");
         for (var i=tables.length; i--;) {
              if (tables.className == strClass) {
                   var gridRows = tables[i].getElementsByTagName("tr");
                   for (var j=gridRows.length; j--;) { if (j%2) { gridRows[j].className = "even"; } }
    window.onload = function () {
         decorateDataGrids("apexir_WORKSHEET_DATA"); // THIS DOES THE STRIPING
    </script>
    <style>
    /* THIS OVERRIDES APEX'S DEFAULT STYLES */
    table.apexir_WORKSHEET_DATA tr.even td {
         background-color:#F1F5FA !important;
    table.apexir_WORKSHEET_DATA td {
         background-color:#FFFFFF !important;
         border:1px solid #B3B3A7 !important;
         padding:4px 8px !important;
    </style>
    onload event strapped to the img -- Thanks!!!
    <img src="#IMAGE_PREFIX#edit.gif" alt="" onload="decorateDataGrids('apexir_WORKSHEET_DATA');">
    Edited by: user11086646 on Jun 9, 2009 7:04 PM

  • Alternating row fill

    I am using ID CS3 to make a 90 page document of tables, though I am formating the tables as tabulated text (size: 7 pt; linespace: 8.455 pt). I am attempting to put in a background pattern for each 5 alternating rows that would (ideally) line up under each set of five rows in the document. Any tips on how to accomplish this? I can come close, but after a few pages the background patterns have already drifted down to the middle of a row.

    Yes, I should have mentioned why I don't use the convert to table option in my CS3. Firstly, it increases the size of the document from 13 MB to over 60 MB (though there is probably a way to get this a bit smaller). Second--though I have not muddled around with the table options for several years--I found it unnecessarily tedious to have to reformat my tables every month when I put in the new data. Back when I did try the table option, there no adequate style sheets. Perhaps the newer versions have them.
    So using just tabbed text with a background of alternating filled rows works faster and keeps the file smaller. Just have to figure out a way to get that background fill to fit properly.

  • Set Table Row Background image

    Hi all,
    I'd like to set a Table row background image, but I only find a way to set a background image for each column, is there any way to set an image  as background for a whole row?

    Hi Pakojones,
    Based on my test, it is not support to make the image tile in a row. The BackgroundRepeat values of tablix is Repeat, RepeatX, RepeatY, or Clip. In SSRS, just chart BackgroundRepeat can be set to Fit.
    Reference: http://technet.microsoft.com/en-us/library/dd239334.aspx
    In SSRS, we can put tablix in a rectangle, then add background image for the rectangle. We can tile the image over the whole tablix. If we want to make the image tile in a row, we can put the single row in a rectangle to work around it. In this situation,
    we have to seamless paste the tablix in the end.
    Alternatively, since the issue is by design, I recommend you that submit this suggestion at
    https://connect.microsoft.com/SQLServer/ . If the suggestion mentioned by customers for many times, the product team may consider to add the feature in the next SQL Server version. Your feedback is valuable
    for us to improve our products and increase the level of service provided.
    Regards,
    Alisa Tang 
    Alisa Tang
    TechNet Community Support

  • Alternating Row colour

    Post Author: vovo
    CA Forum: General
    Is it possible to have alternating row colour? Eg. First row background colour is white and second row background colour is grey. Can somebody help me? Thanks.

    Post Author: vovo
    CA Forum: General
    Got it to work... Shared numbervar RowCount;whileprintingrecords;RowCount :=RowCount+1;if (RowCount mod 2=1) then    crWhiteelse    color( 47, 179, 79);

  • Want robust solution for alternating row color, resetting every group

    I would like a solution for displaying an alternating row color for my detail rows that resets every group, so that row 1 is always gray.
    Our Crystal designer provided this code to me:
    @rowcnt formula, suppressed, placed in Detail row:
    Shared numbervar rowcnt;
    rowcnt := rowcnt + 1;
    @resetrowcnt, suppressed, placed in Group row:
    Shared numbervar rowcnt;
    rowcnt := 0;
    Formatting formula, placed in Color in Detail > Section Expert:
    Shared numbervar rowcnt;
    if Remainder(rowcnt, 2) <> 0 then
    color(241,241,241)
    else
    crWhite
    This was working fine for me.
    However, it is suddenly not working in one of my reports.
    The report does happen to have two groups (rowcount.png).
    When the report is run, all rows are colored (rowcount02.png).
    This report was previously working fine!  I'm not sure what changed.
    In any case... surely there must be standard code to do this very standard formatting.
    I would be very grateful if someone could post some robust code to accomplish the following:
    REPORT DATA IN DETAIL ROW, ALTERNATE ROW BANDING:
    - Data in Detail row displays alternating row colors
    - Odd rows are always shaded, even rows not
    - Banding resets every group / does not continue pattern from previous group
    REPORT DATA IN GROUP ROW, ALTERNATE ROW BANDING:
    Some of our reports place row data in a group row (just the way it happened).
    If you could also modify your code in this case.
    Thank you!

    Hi Abhilash/Sastry, since I'm going to switch to Sastry's formulas, could you please confirm correctness of the following. I can't actually run this report, I can only provide it to our London office, bit of a lag for testing.
    @resetrowcnt:
    Whileprintingrecords;
    Numbervar cnt:=0;
    @rowcnt:
    Whileprintingrecords;
    if {HedgeDetails.StrategyID} <> previous({HedgeDetails.StrategyID}) and
    {HedgeDetails.DealID} <> previous({HedgeDetails.DealID}) then
         Numbervar cnt:=cnt+1;
    Details section (Suppress):
    not(OnFirstRecord) and
    {HedgeDetails.StrategyID}=previous({HedgeDetails.StrategyID}) and
    {HedgeDetails.DealID}=previous({HedgeDetails.DealID})
    Please note: Suppress checkbox is selected AND the above formula is entered.
    Details section (Color):
    Whileprintingrecords;
    Numbervar cnt;
    if cnt mod 2 <> 0 Then color(241,241,241) else crwhite

Maybe you are looking for

  • Can I access my old iWeb account on a new computer?

    My computer crashed and with it went what I had built on iWeb. It is published to a site. My question is - can I somehow get everything back onto my new iWeb app without having to rebuild? And if I do have to rebuild how do I get it to overwrite the

  • Can I use a different ID for app store than icloud on iphone?

    In our household we share an ID for itunes so that we do not have to buy a separate instance of an app for each device we own. This causes a problem when someone wants to use their phone to buy an app since there is a different ID on the iphone than

  • "Manually" creating U3D files to import into Acrobat XI

    Has anyone here ever successfully tried to "manually" create a U3D file and open it in a Acrobat XI to save it as a PDF file? I am currently coding an U3D export filter for our self-developed CAD application. The resulting files (containing simple po

  • Can I use Lumia 920 charger to charge Lumia 925 ?

    I used tonight my friend Lumia 920 charger (EU ver) to charge my Lumia 925 for a little bit, is this safe for my 925 ? Thx.

  • Lumia 620 vibration issue and camera video recordi...

    Hello, I recently purchased a Lumia 620 and facing some issues with it. The vibration is not at all working. I have updated to Lumia black. And how to focus in video camera. It ain't focusing during recording. Please help me..