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 13 of 13

Thread: change color according to the value of a cell

  1. #1
    Junior Member
    Join Date
    Jul 2020
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default change color according to the value of a cell

    I read a Mysql table and show its content in a JTable. Actually I make a conversion from the mysql.table to what I really will display by using a switch

     {
      case "V" : dummy = String.valueOf('V');
                 if (dummy.equals(pippo)) { pippo = "SA"; row.add(pippo); } break;
      case "X" : dummy = String.valueOf('X');
                 if (dummy.equals(pippo)) { pippo = "x"; row.add(pippo); } break;    
      case "H" : dummy = String.valueOf('H');
                 if (dummy.equals(pippo)) { pippo = "BM"; row.add(pippo); } break; 
      case "L" : dummy = String.valueOf('L');
                 if (dummy.equals(pippo)) { pippo = "BP"; row.add(pippo); } break;  
      ....
    }

    What I would like is to set bg-color = lightgray when pippo = "SA", pink when pippo = "BM" and so on

    this is the renderer

    for (int column = 0; column < table.getColumnCount(); column++)
    {
        TableColumn tableColumn = table.getColumnModel().getColumn(column);
        int preferredWidth = tableColumn.getMinWidth();
        int maxWidth = tableColumn.getMaxWidth();
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        for (int row = 0; row < table.getRowCount(); row++) {
            TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
            Component cell = table.prepareRenderer(cellRenderer, row, column);
     
            int width = cell.getPreferredSize().width + table.getIntercellSpacing().width;
            preferredWidth = Math.max(preferredWidth, width);
            if (preferredWidth >= maxWidth) {
                preferredWidth = maxWidth;
                break;
            }
        }
        tableColumn.setPreferredWidth( preferredWidth );
     
        for (int row = 0; row < table.getColumnCount(); row++) {
            DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
            centerRenderer.setHorizontalAlignment(JLabel.CENTER);
     
            table.getColumnModel().getColumn(row).setCellRenderer(centerRenderer);
        }
    }

    How can I obtain what I want?

    Thank you in advance

    paps

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

    Default Re: change color according to the value of a cell

    Do you have the code that will do this: set bg-color?
    Then define a variable of type Color and assign if the desired color using if statements:
      Color theColor = null;
      if(aString.equals("wantPink"))  
          theColor = Color.PINK
       // other tests here
    Then use theColor with the set bg-color method.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jul 2020
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: change color according to the value of a cell

    Nope, dont have the code to set bg-color. Any suggestion?
    Thank you for the code to insert in the switch

    paps

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

    Default Re: change color according to the value of a cell

    Look at the API doc for the class that you want to change color for to see if it has a method to do that.
    http://docs.oracle.com/javase/8/docs/api/index.html
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Jul 2020
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: change color according to the value of a cell

    Thank you. You gave me the "bible" of java. Will study it, but will ask again i necessary.

  6. #6
    Junior Member
    Join Date
    Jul 2020
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: change color according to the value of a cell

    Here we are
    I read some documentation about Color, TableCellRenderer, ... but it doesnt work

     
    JTable table = new JTable(dataVector, columnNamesVector);
     
                table.setFont(new Font("Verdana", Font.PLAIN, 11));
                table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
     
                for (int column = 0; column < table.getColumnCount(); column++) {
     
                TableColumn tableColumn = table.getColumnModel().getColumn(column);
                int preferredWidth = tableColumn.getMinWidth();
                int maxWidth = tableColumn.getMaxWidth();
                table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
                for (int row = 0; row < table.getRowCount(); row++) {
     
                TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
                String value = String.valueOf(table.getValueAt(row, column));  //<-- this will be used when the below code will act as I want
     
                Component cell = table.prepareRenderer(cellRenderer, row, column);
                Color mycolor = new Color(0, 0, 255); //<----
                cell.setBackground(mycolor);              //<----- cell background is always white
               // Tried with cell.setBackground(Color.RED); but nothing
     
                int width = cell.getPreferredSize().width + table.getIntercellSpacing().width;
                preferredWidth = Math.max(preferredWidth, width);
                if (preferredWidth >= maxWidth) {
                    preferredWidth = maxWidth;
                    break;
                }
            }

    Thank you for your patience
    paps

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: change color according to the value of a cell

    but it doesnt work
    Can you make a small, complete program that compiles and executes for testing to show the problem?

    Did you try Google? Here's an interesting item:
    https://stackoverflow.com/questions/...nge-cell-color
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Junior Member
    Join Date
    Jul 2020
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: change color according to the value of a cell

    Hi,
    Im in a nightmare. I have lot of questions and will start other questions
    I found a classe which should solve my problem(I hope) but cant call from inside the above render. My idea is to insert CustomerCellRenderer after the rendering of the value in the cell
    Something like this

    // The "old" CellRenderer
    TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
                String value = String.valueOf(table.getValueAt(row, column)); 
     
                Component cell = table.prepareRenderer(cellRenderer, row, column);
     
               CustomCellRenderer colore = new CustomCellRenderer(); //I get as many errors as possible
                colore.getTableCellRendererComponent(table, value, true, true, row, column);
     
                Color mycolor = new Color(0, 0, 255);
                cell.setBackground(mycolor);
     
                int width = cell.getPreferredSize().width + table.getIntercellSpacing().width;
                preferredWidth = Math.max(preferredWidth, width);
     
     
            //  We've exceeded the maximum width, no need to check other rows
                if (preferredWidth >= maxWidth) {
                    preferredWidth = maxWidth;
                    break;
                }


    This is the class I suppose could do my job. Its in the same java file as the "old" renderer

    public class CustomCellRenderer extends JLabel implements TableCellRenderer {
     
         private displayResult changeColor; //the class with "old" renderer
         public CustomCellRenderer(displayResult changeColor) {
         this.changeColor = changeColor; }
     
        public  TableCellRenderer defaultCellRenderer;
     
        public CustomCellRenderer(TableCellRenderer defaultCellRenderer) {
            this.defaultCellRenderer = defaultCellRenderer;
        }
        public Component getTableCellRendererComponent(JTable mytable, Object ovalue, boolean isSelected, boolean hasFocus, int row, int column) {
            String val = (String) ovalue;
            Component c = defaultCellRenderer.getTableCellRendererComponent(mytable, ovalue, isSelected, hasFocus, row, column);
            if (c != null) {
                if (val.equals("0h")) {
                    c.setForeground(Color.RED);
                } else {
                    c.setForeground(mytable.getForeground());
                }
                return c;
            } else return null;
        }
    }

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: change color according to the value of a cell

    Can you make a small, complete program that compiles, executes and shows the problem?
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Junior Member
    Join Date
    Jul 2020
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: change color according to the value of a cell

    If you use mysql I could send a part of the sql file sql I use to read data otherwise... I dont know how to do it. The project is really small (two .java files) which I could reduce to one passing fixed data to the query.

    paps

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: change color according to the value of a cell

    Remove the mysql usages and replace them with hardcoded values so mysql is not needed for testing.
    If you don't understand my answer, don't ignore it, ask a question.

  12. #12
    Junior Member
    Join Date
    Jul 2020
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: change color according to the value of a cell

    Here it is.

    package displayresult;
     
     
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Font;
     
    import java.util.ArrayList;
    import java.util.Vector;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
     
    public class DisplayResult extends JFrame {
     
        public void getTableCellRendererComponent(CustomCellRenderer getTableCellRendererComponent) {
        }  
     
       public String pippo;
       public String setBg;
       public Object getValueAt;
     
       public static void main(String[] args){  
            DisplayResult frame = new DisplayResult();
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            frame.setSize(500, 150);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
     
        public DisplayResult()
        {
            super("tu surela");
     
     
     
            ArrayList columnNames = new ArrayList();
            ArrayList data = new ArrayList();
     
     
                int columns = 4;
     
                //  Get column names
                String A="";
                for (int i = 1; i <= columns; i++) {
                    String Ii = String.valueOf(i);   
                    String columnVal = A+Ii;
                    columnNames.add(columnVal );
                }
     
                //  Get row data
                for (int zz = 1; zz <= 5; zz++)
                {
                    ArrayList row = new ArrayList(columns);
     
                    for (int i = 1; i <= columns; i++)
                    {  
                        String Zz = String.valueOf(zz);
                        String Ii = String.valueOf(i * 3.5); 
     
                        pippo = Ii+Zz;
                        row.add(pippo);
                    }
                    data.add( row );
                }
     
     
            // Create Vectors and copy over elements from ArrayLists to them
            // Vector is deprecated but I am using them in this example to keep 
            // things simple - the best practice would be to create a custom defined
            // class which inherits from the AbstractTableModel class
            Vector columnNamesVector = new Vector();
            Vector dataVector = new Vector();
     
            for (int i = 0; i < data.size(); i++)
            {
                ArrayList subArray = (ArrayList)data.get(i);
                Vector subVector = new Vector();
                for (int j = 0; j < subArray.size(); j++)
                {
                    subVector.add(subArray.get(j));
                }
                dataVector.add(subVector);
            }
     
            for (int i = 0; i < columnNames.size(); i++ ) {
                columnNamesVector.add(columnNames.get(i));
            }
                JTable table = new JTable(dataVector, columnNamesVector);
     
                table.setFont(new Font("Verdana", Font.PLAIN, 11));
                table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
     
                for (int column = 0; column < table.getColumnCount(); column++) {
     
                TableColumn tableColumn = table.getColumnModel().getColumn(column);
                int preferredWidth = tableColumn.getMinWidth();
                int maxWidth = tableColumn.getMaxWidth();
                table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
                for (int row = 0; row < table.getRowCount(); row++) {
     
                TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
                Object value = table.getValueAt(row, column); 
     
                Component cell = table.prepareRenderer(cellRenderer, row, column);
     
                //TheClass.theMethod();
                //CustomCellRenderer.getTableCellRendererComponent(table, value, true, true, row, column); <-------------------------
     
                Color mycolor = new Color(0, 0, 255);
                cell.setBackground(mycolor);
     
                int width = cell.getPreferredSize().width + table.getIntercellSpacing().width;
                preferredWidth = Math.max(preferredWidth, width);
     
     
            //  We've exceeded the maximum width, no need to check other rows
                if (preferredWidth >= maxWidth) {
                    preferredWidth = maxWidth;
                    break;
                }
            }
     
     
                tableColumn.setPreferredWidth( preferredWidth );
     
                for (int row = 0; row < table.getColumnCount(); row++) {
                    DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
                    centerRenderer.setHorizontalAlignment(JLabel.CENTER);
                    table.getColumnModel().getColumn(row).setCellRenderer(centerRenderer);
                }
    }
                JScrollPane scrollPane = new JScrollPane( table);
                //JScrollPane sscrollPane = 
                new JScrollPane(scrollPane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                Component add = getContentPane().add( scrollPane );
     
                JPanel buttonPanel = new JPanel();
                getContentPane().add( buttonPanel, BorderLayout.NORTH );
    }
     
     
     
     
     
     
    public class CustomCellRenderer extends JLabel implements TableCellRenderer {
     
        public  TableCellRenderer defaultCellRenderer;
     
        public CustomCellRenderer(TableCellRenderer defaultCellRenderer) {
            this.defaultCellRenderer = defaultCellRenderer;
        }
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                                            boolean hasFocus,  int row, int column) {
            String val = (String) value;
            Component c = defaultCellRenderer.getTableCellRendererComponent(table, value, true, true, row, column);
            if (c != null) {
                if (val.equals("0h")) {
                    c.setForeground(Color.RED);
                } else {
                    c.setForeground(table.getForeground());
                }
                return c;
            } else return null;
        }
    }
    }

  13. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: change color according to the value of a cell

    Ok, where are the comments in the code that describe what it is supposed to do?

    Have you looked at the tutorial?
    https://docs.oracle.com/javase/tutor...nts/table.html

    Linked from: http://docs.oracle.com/javase/tutori...ybigindex.html
    SAVE THE ABOVE
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. How to change color in blue j
    By RITESH92 in forum Java IDEs
    Replies: 2
    Last Post: March 21st, 2018, 02:23 PM
  2. Replies: 2
    Last Post: June 9th, 2014, 04:06 PM
  3. How do I change the color of my cursor?
    By Chokladmunken in forum What's Wrong With My Code?
    Replies: 4
    Last Post: January 17th, 2014, 10:54 AM
  4. Trying To Change The Color Of JScrollBar
    By Damian3395 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: July 4th, 2013, 06:40 PM
  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

Tags for this Thread