Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Problem changing background color of JTable row

  1. #1
    Junior Member
    Join Date
    Jan 2022
    Posts
    20
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Problem changing background color of JTable row

    I am using the following code to change the background colour of row where the first cell is not blank.
    It works but it also changes the colour of highlighting of selected rows.
    I want the background colour change to persist but the user can click anywhere and see the standard highlight.
    I add the hasFocus check to turn the background blue when selected but only the selected cell is highlighted in blue.
    Essentially I want every x lines of the table to be a different colour, but still have normal selection colours.
    /*
     * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
     * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
     */
     
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableModel;
     
    /**
     *
     * @author noone
     */
    public class ConversationsTable extends JTable {
     
        public ConversationsTable(TableModel dm) {
            super(dm);
            this.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
            {
                @Override
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
                {
                    final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                    System.out.println("row " + row);
                    String id = table.getValueAt(row,0) != null ? table.getValueAt(row,0).toString(): "";
                    if(id.trim().length() > 0) {
                            //System.out.printf("rc %d %d %d\n", row, column, i);
                            c.setBackground(Color.CYAN);    // .LIGHT_GRAY);
                    }else{
     
                        if(hasFocus){
     
                           c.setBackground(Color.BLUE);
     
                        }else{
                            c.setBackground(Color.WHITE);
                        }
                    }
                    return c;
                }
            });
        }
    }

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem changing background color of JTable row

    Can you provide code for testing? There is no main method in the posted code.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jan 2022
    Posts
    20
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Problem changing background color of JTable row

    Here is a main file to use to test with.
     
    import java.util.HashSet;
    import java.util.Set;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.table.DefaultTableModel;
     
    /*
     * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
     * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
     */
     
    /**
     *
     * @author noone
     */
    public class TestJTable {
        public static void main(String[] args){
            DefaultTableModel tm = new DefaultTableModel(new Object[]{"column A", "column B" ,"column C"}, 10); 
            tm.insertRow(0, new Object[]{1, "testb", "test1c"});
            tm.insertRow(1, new Object[]{"", "testb", "test1c"});
            tm.insertRow(2, new Object[]{"", "testb", "test1c"});
            tm.insertRow(3, new Object[]{2, "testb", "test2c"});
            tm.insertRow(4, new Object[]{"", "testb", "test2c"});
            tm.insertRow(5, new Object[]{"", "testb", "test2c"});
            tm.insertRow(6, new Object[]{"", "testb", "test2c"});
            tm.insertRow(7, new Object[]{3, "testb", "test3c"});
            tm.insertRow(8, new Object[]{"", "testb", "test3c"});
            ConversationsTable table = new ConversationsTable(tm); 
            JFrame frame = new JFrame(); 
            frame.setSize(800, 600);
            frame.add(new JScrollPane(table));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
            frame.setVisible(true);
     
        }
    }

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem changing background color of JTable row

    Thanks, now can execute the code.
    Can you describe in more detail what is wrong with the code or what you want to happen differently?

    At the start of execution, the lines with numbers in col A are colored CYAN, the others are white.
    When a cell is clicked on, the cell's color changes to BLUE, except for the cells colored CYAN where only a border changes to BLUE.
    When another cell is clicked, the previously clicked cell's color is restored to what it was and the clicked cell is colored BLUE as above.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Jan 2022
    Posts
    20
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Problem changing background color of JTable row

    I want to set the background colour of the row where a start of a record is. This is a row where column 0 has a value.
    That you can see in the demo code as cyan.
    Unfortunately the only way to do this (as far as I can tell) is to take over the cell renderer.
    In doing that the default colouring of table row selection highlights is also taken over.
    In the normal operation of a table, when you click on a cell the entire line is highlighted a dark blue.
    After taking over the cell renderer, the entire row is still being highlighted, but now the colour stated in the cell renderer
    }else{
                            c.setBackground(Color.WHITE);
                        }
    ...is the colour used to highlight the row. Since that is now white and the foreground colour of a highlighted row is also white the text essentially disappears, (except the specific cell clicked on which has the focus and gets coloured blue).

    All I want is to have the background colour of the row that starts a record, be a different colour and all other colours including selection highlighting to remain as their defaults.

    It looks like if I want to restore the selection colours, I will have to check if the cell being rendered has the focus, and then backtrack from the column selected to column 0 and paint each cell in the row a blue background colour (recoding functionality that already exists, but is removed by overriding the cell renderer). (If that is the only way to paint a row a different color)
    Or maybe store a list of rows that are to be cyan and check if the current cell is on that row and not selected and paint it cyan or some such.

    What seems like it should be a basic property of a table, is obfuscated to overriding what is essentially painting method. Obfuscated to the point that I would call it a flaw in design, unless I am missing something.
    (Cell rendering and selection highlighting should be separate functionalities imho)

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem changing background color of JTable row

    Can you write a simple description of what happens when a cell is clicked and how you want to change that?
    Just a list of what the user does and what the program does and what you want to be different.
    For example:
    Starts with lines with contents in col A colored CYAN
    Click on r=1,c=A > cell at 1,A changes to ...
    Click on r=2,c=A > cell at 1,A changes to ..., cell at 2,A changes to ... <<< Here I want ... instead
    etc
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Jan 2022
    Posts
    20
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Problem changing background color of JTable row

    When you click on a cell the entire row is highlighted.

    That is the behaviour I want.
    Its even easier to show you. Just don't use the cell renderer and run the code.
    When you click on any cell you will see the row selected and highlighted a dark blue.
    import java.util.HashSet;
    import java.util.Set;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.table.DefaultTableModel;
     
    /*
     * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
     * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
     */
     
    /**
     *
     * @author noone
     */
    public class TestJTable {
        public static void main(String[] args){
            DefaultTableModel tm = new DefaultTableModel(new Object[]{"column A", "column B" ,"column C"}, 10); 
            tm.insertRow(0, new Object[]{1, "testb", "test1c"});
            tm.insertRow(1, new Object[]{"", "testb", "test1c"});
            tm.insertRow(2, new Object[]{"", "testb", "test1c"});
            tm.insertRow(3, new Object[]{2, "testb", "test2c"});
            tm.insertRow(4, new Object[]{"", "testb", "test2c"});
            tm.insertRow(5, new Object[]{"", "testb", "test2c"});
            tm.insertRow(6, new Object[]{"", "testb", "test2c"});
            tm.insertRow(7, new Object[]{3, "testb", "test3c"});
            tm.insertRow(8, new Object[]{"", "testb", "test3c"});
            JTable table = new JTable(tm); 
            JFrame frame = new JFrame(); 
            frame.setSize(800, 600);
            frame.add(new JScrollPane(table));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
            frame.setVisible(true);
     
        }
    }
    Now go back and look at the version with the cell renderer and its easy to see that the selection highlighting has gone haywire.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem changing background color of JTable row

    That is the behaviour I want.
    If the code in post#7 does what you want, then why not use that code.
    I suspect you want more than what is in that code or you wouldn't be here.
    Can you explain what more you want that is not provided by the code in post#7?
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Jan 2022
    Posts
    20
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Problem changing background color of JTable row

    Now, you have to read everything I write. You must not ignore parts.
    This is what I wrote in post #1
    I am using the following code to change the background colour of row where the first cell is not blank.
    It works but it also changes the colour of highlighting of selected rows.
    In post #7 I show what the selection behaviour I want looks like. But that code doesn't fulfill "change the background colour of row where the first cell is not blank".
    Also in post #7 I make it quite clear that the selection colours "go haywire".
    Did you not notice that?

    In any case, maybe you will better understand when you look at the following code that actually does do all of what I want.
    Its rigmarole due to the combined nature of the cell background rendering and cell selection rendering in the JTable, but it does seem to work.
    (I am certain that the JTable in the Swing library is in need of design change but that is irrelevant to this thread.)

    First I added a list to contain the indexes of the rows that are the start of a new record (to the class that extends JTable):
    public class ConversationsTable extends JTable {
        private static final List<Integer> recordStartRows = new ArrayList<>();
    Next I rearranged the cell renderer to filter 'row is a start of record' and 'row is selected', 'row is not a start of record' and 'row is selected'. In each of these cases the background colour will be different.
                @Override
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
                {
                    final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                    if(isRecordStartRow(row)){
                        if(table.getSelectedRow() == row){
                            c.setBackground(Color.BLUE);
                        }else{
                            //System.out.printf("rc %d %d %d\n", row, column, i);
                            c.setBackground(Color.CYAN);    // .LIGHT_GRAY);
                        }
                    }else{
                        if(table.getSelectedRow() == row){
                           c.setBackground(Color.BLUE);
                        }else{
                            c.setBackground(Color.WHITE);
                        }
                    }
                    return c;
                }
    This is the utility function isRecordStartrow():
        private static boolean isRecordStartRow(int row){
            return ConversationsTable.recordStartRows.contains(row);
        }
    I get that it isn't always easy to understand where another person is going with their code.
    In this case all the info was in the posts and I really couldn't have made it any clearer.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem changing background color of JTable row

    Ok, so is this what you are trying to do:
    Mark rows with data in col A in CYAN color
    If one of those rows is selected by a click, show the row as selected and not with the CYAN color.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. [SOLVED] background color
    By keepStriving in forum AWT / Java Swing
    Replies: 4
    Last Post: December 3rd, 2013, 05:33 PM
  2. Changing a JButton background
    By idanbob in forum AWT / Java Swing
    Replies: 5
    Last Post: September 15th, 2013, 12:26 PM
  3. Setting background color to translucent?!?!
    By syregnar86 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: August 23rd, 2013, 07:58 AM
  4. mode.addRow with background color
    By nsyncpilu in forum AWT / Java Swing
    Replies: 3
    Last Post: December 15th, 2011, 09:50 AM
  5. set Background Excel cell color using POI API
    By ngamal in forum What's Wrong With My Code?
    Replies: 2
    Last Post: March 26th, 2011, 11:20 AM