Setting the foreground in JTable cells conditionally.

I have a JTable which contains two columns adjacent to each other, both containing numbers (Floats).
If the number in the cell at a given row of column2 is greater than the number in the corresponding cell of column1, I want to set < row, column2 >'s text/foreground to red.
i.e.: If 0, 2 value > 0, 1 value: Set 0, 2 foreground to red
Also, I want to do this for all the cells in the second column whose values meet the criterion, simultaneously.
My question:
Am I right in assuming that this is a routine task in Java, and that there are well established ways of doing this?
If so, can anyone post or point me to some example code? If this is a wheel, I would hate to reinvent it.
Many thanks in advance.

karen,
I suggest you just make the whole cell the "select" colour, especially if it's a background colour... it gives the user a better impression of what it will look like in the "whatever".... even if you think it doesn't look so good "in itself".
The trick, is to use contrastingly dark or light forground colour.
If you really must have small region to the left containing a text colour then just make it another column in the table.
keith.

Similar Messages

  • Set the colum in JTable to NotEditable

    How can I set the colum in JTable so it's not editable. The table model is in the same class with the JTable.

        aTable.setModel(new DefaultTableModel(columnHeader, 0) {
          public boolean isCellEditable(int row, int col) {
            return (col != yourNonEditableColumn);
        });

  • 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.

  • Disabling the border on JTable cell renderer

    Hello all
    I've developed a JTable that doesn't allow cell editing and only allows single-row selection. It works fine, I've allowed the user to press <tab> to select the next row or click the mouse to select any row. The row selected is high-lighted and I'm happy with how it works.
    However:
    Due to the single-row selection policy, it doesn't make sense to display a border around any cell that has been clicked. I would therefore like to prevent the JTable from displaying a border on any cell the user has clicked.
    I've checked out the API documentation for JTable and the closest I've been able to get is to construct a DefaultTableCellRenderer and then use JTable.setDefaultRenderer. The problem is I don't know how to set the DefaultTableCellRenderer to NOT display a border when selected.
    I can see a method called getTableCellRendererComponent which takes parameters that seemingly return a rendering component, but should I specify isSelected = true and isFocus = true? And what should I do once I have the Component? I've tried casting it to a JLabel and setBorder(null) on it, but the behaviour of the table remains the same.
    I've tried all sorts of things but to no avail. I'm finding it all a bit confusing...
    Why oh why isn't there simply a setTableCellRendererComponent()? ;)

    JTable can potentially use multiple renderers based on the type of data in each column, so you would need to create multiple custom renderers using the above approach. The following should work without creating custom renderers:
    table = new JTable( ... )
         public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
              Component c = super.prepareRenderer(renderer, row, column);
              ((JComponent)c).setBorder(null);
              return c;
    };

  • Setting two JTextFields inside JTable cell

    hi,
    I am really stick trying to figure out how to set two cells inside a JTable cell. This needs to be done because if there is a value already inside the cell then i want to drop another value - this new value should be displayed inside another cell but along with the other value already in the cell.
    I assume that i would need to create two JTextFields.
    But can anyone help me further please.

    That should be a simple issue of customizing table cell editor and renderer.
    See tutorials.

  • Dynamically set font in a JTable cell

    Hi there,
    i have a JTable, and a JTCombo box containing all the system fonts available. The JTable is made up of my own class called myCell which can be seen below. I have also implemented my own custom renderer. What i would like to do is when the user selects a new system font, the text that is then typed into the JTable to be of that font. If the system font is changed again, i would like any new text to be of the new font, and the old fonts remain the same (i hope that makes sense!) Anyway, im quite stuck about this - i have tried messing around with the cellrenderer but all the text in all the cells changes to the new font. Does anyone know how to do this? many thanks, Rupz
         public myCell(int aRow,int aCol,Object someValue, TreeSet somecells, String aFormula){
              row = aRow;
              col = aCol;
              value = someValue;
              expression = aFormula;
              references = somecells;
         }

    First of all the Java standard for class names us to use upper case characters for the first letter of each word. So your class should be MyCell.
    Now your MyCell class need to keep the Font as one of its properties. Maybe you would override the JTable getCellEditor(...) method such that if the Font property for the cell is null, then set the cell Font to the current default Font. The renderer would then use the Font from the cell when it is non-null.

  • Can not show the JCheckBox in JTable cell

    I want to place a JCheckBox in one JTable cell, i do as below:
    i want the column "d" be a check box which indicates "true" or "false".
    String[] columnNames = {"a","b","c","d"};
    Object[][] rowData = {{"", "", "", Boolean.FALSE}};
    tableModel = new DefaultTableModel(rowData, columnNames);
    dataTable = new JTable(tableModel);
    dataTable.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(new JCheckBox()));
    But when i run it, the "d" column show the string "false" or "true", not the check box i wanted.
    I do not understand it, can you help me?
    Thank you very much!
    coral9527

    Do not use DefaultTableModel, create your own table model and you should implement the method
    getColumnClass to display the boolean as checkbox ...
    I hope the following colde snippet helps you :
    class MyModel extends AbstractTableModel {
              private String[] columnNames = {"c1",
    "c2"};
    public Object[][] data ={{Boolean.valueOf(true),"c1d1"}};
         public int getColumnCount() {
         //System.out.println("Calling getColumnCount");
         return columnNames.length;
    public int getRowCount() {
    //System.out.println("Calling row count");
    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 true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    data[row][col] = value;
    fireTableCellUpdated(row, col);

  • How to set the Border of a cell in excel sheet

    dear all,
    using OLE2 i want to set the cell's border in an excel sheet
    so whats the property for that?
    ole2.set_property(WorkCell,???, ???);
    thanks and best regards,
    very urgent plz
    thanks in advance

    Could you, please, definitly remove the "urgent" word from your vocabulary when you post on this forum. We are all volonteers and not paid at all to answer the qestions. I repeat one more time that there is no post more urgent than another.
    If you are so in a hury, as said Gerd, contact the Oracle support.
    Francois

  • Does SSRS dynamically set the alignment of table cells based on the majority of cell types in the column???

    This is the first time I've run into this, but it appears that SSRS is setting the text-align based on the other cells in the column.  I have cells being set with either a dataset item of type System.Double or to "--" when Is Nothing evaluates
    to true.  I never noticed before that if the majority of the cells in the column are Nothing, then the few that aren't Nothing get aligned to the left along with all of the "--" text items.  And now I also see columns where the opposite
    is also happening, where if the majority of the cells in the column are numeric values, then everything is aligned right, even the few "--" items there.  I'm only using Default TextAlign and VerticalAlign, and no Indent, SpaceAfter or SpaceBefore,
    nor any concatenated text or embedded preserved spaces.
    Has anyone else in the SSRS universe seen this, and does anyone know why or have a good workaround for it?
    Thanks in advance : )

    Are you viewing the report in html format or are you looking in some other format like Excel,CSV etc?
    Please Mark This As Answer if it solved your issue
    Please Mark This As Helpful if it helps to solve your issue
    Visakh
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • How to set the text of a cell in Numbers to vertical direction? Tks.

    Hi
    In Numbers, please tell me how to switch the text of a cell to vertical direction?
    Tks.

    Hi Kyle,
    In Numbers, nothing having to do with a table can be rotated. (In Pages an entire Table can be rotated, but not text within a Table.)
    There have been many suggestions posted here over the life of iWork for vertical labels. Most fall into three categories:
    1. Type one letter, Option-Return, type another letter, Option-Return, and so forth.
    2. Type label in a Text Box, rotate the box, position the box over the table, covering the cell where you need a label.
    3. Create a PDF graphic with rotated text and insert it into table cell as Background Fill.
    The third option is clearly the best. The steps for option three are:
    Insert Text Box
    Type label into the box
    Rotate the text box
    Select the text box (not the text inside the box)
    Command-C
    Switch to Preview.app
    Command-N
    Command-C
    Switch to Numbers
    Click on Cell where the label goes
    Command-V
    It sounds worse than it is. You can reuse the Text Box so you don't end up with a sheet full of them.
    Regards,
    Jerry

  • Set Background/Foreground color for Cell Renderer in JComboBox

    Hello,
    I was wondering if there is a way to change default settings for when I browse items under a JComboBox's cell renderer? I want the item's color to change (to what I set it to), when mouse enters the item. As of now, the cell's background color changes to Blue when I enter it. Is this default for JComboBox or might it have been set somewhere, that I need to look into?
    Please let me know if there are ways to do this.
    Thanks!
    Message was edited by:
    programmer_girl

    Here's my SSCCE:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JComboBox;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.text.DefaultHighlighter;
    public class MyComboBoxTest extends JPanel {
          * @param args
         String[] patterns = {"pattern1","pattern2","pattern3"};
         public MyComboBoxTest()
              JPanel patternsPanel = new JPanel();
            setMinimumSize(new Dimension(100, 100));
            JComboBox patternList = new JComboBox(patterns);
            final JTextField editor = (JTextField) patternList.getEditor().getEditorComponent();
            patternList.setEditable(true);
            this.add(patternsPanel);
            patternsPanel.add(patternList);
            patternList.addActionListener(new ActionListener()
                 public void actionPerformed(ActionEvent e)
                      editor.setSelectedTextColor(Color.WHITE);
                      editor.setForeground(Color.WHITE);
                      try{
                           editor.getHighlighter().addHighlight(0, editor.getText().length(),new DefaultHighlighter.DefaultHighlightPainter(Color.BLUE));
                           } catch (Exception ex){
                                ex.getMessage();
            editor.addMouseListener(new MouseAdapter()
                 public void mouseClicked(MouseEvent e)
                      editor.getHighlighter().removeAllHighlights();
                      editor.setForeground(Color.BLACK);
                      editor.setSelectedTextColor(Color.BLACK);
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              JFrame frame = new JFrame("My ComboBox Demo");
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setSize(100, 100);
            frame.getContentPane().add(new MyComboBoxTest());
            frame.setLocation(50, 50);
            frame.pack();
            frame.setVisible(true);
    }

  • Is there some way to set focus on a JTable Cell?

    Hi,
    I have used JDK6 with a JTable that has some cells not-editabled and others editable.
    Then, when the user types TAB key, I would like to change to next editabled cell, jumping out the not-editables. Is there a way to do this?
    Thanks

    check out this thread:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=509913
    Theoretically you could modify the FocusTraversalPolicy but I've never done that.
    Message was edited by:
    Jaspre

  • How can I set the foreground/background color after using CSPickColor()?

    Hello all,
    Is there any one who has experience on changing foreground or background color using Photoshop Plug-in SDK?
    Currently I can get a returned color from CSPickColor(), but have no idea how to use it.
    Thanks!

    You can try a linear-gradient that starts at gray 0% and ends at white <whatever the percentage the thumb is at>.
            final Node track = slider.lookup(".track");
            slider.valueProperty().addListener(new ChangeListener<Number>() {
                public void changed(ObservableValue<? extends Number> ov, Number t, Number t1) {
                    double pct = (t1.doubleValue()-slider.getMin())/(slider.getMax()-slider.getMin())*100;
                    track.setStyle("-fx-background-color: linear-gradient(to right, gray, gray " + pct + "%, white" + pct + "%, white);");
            });Edited by: dgrieve on Apr 12, 2012 12:19 PM

  • Dynamically set the itemStyle depending on a condition

    Hello everybody,
    hope you are fine.
    would you please tell me that is it possible to set a Item's ItemStyle dynamically?
    suppose i want if i come from page1.PG then Item1's style should be MessageInputText
    and if i come from page2.PG then Item1's style should be MessageStyledText
    please suggest

    I am taking an example for MessageTextInput bean....
    public void processRequest(OAPageContext pageContext, OAWebBean webBean)
        super.processRequest(pageContext,webBean);
        OAMessageTextInputBean startdate = (OAMessageTextInputBean)webBean.findChildRecursive("StartDate"); //StartDate is the ID of the bean
       if (startdate  != null)
           startdate.setRendered(false);
    }Thanks
    --Anil                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • 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!

Maybe you are looking for

  • Certain purchased songs won't download to ipod??

    I've had this problem for quite a while. I plug the ipod in and it never downloads the certain songs. I have tried unchecking them and connecting the ipod then checking them back and connecting it again and it will say that it's copying the songs but

  • Open/Transfer/close Dataset and delimiting

    Hi people hi have a situation regarding open/transfer/close dataset and delimits. I have a submit program that calls any other via variants. It works fine with using list_to_memory, convert to ascii, and open dataset. I can download the report in exc

  • Problem on receiving IDoc

    I have configured 3 dialog processes dedicated for processing inbound IDoc. But when an IDoc is received but the 3 dialogs are still processing, it will become error for that IDoc. Are there any ways to configure the system so that the inbound IDoc i

  • Powerbook 17" and 20" display

    Hi evevryone, I am thinking about buying the 20" display for an extended desktop for my powerbook 17", just wondered if there are any issues with this? i was using a sony sdm-hs95p and this is currently for sale on ebay but i figured i wanted a wide

  • Layout for one-child container

    Fairly often it comes up that I want to put just one child in a container, and for it to resize etc. with the container. What layout do people usually use in these circumstances?