How to set cell background color for JCheckBox renderer in JTable?

I need to display table one row with white color and another row with customized color.
But Boolean column cannot set color background color.
Here is my codes.
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.TreeSet;
public class BooleanTable extends JFrame
    Object[][] data = {{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE}};
    String[] header = {"CheckBoxes"};
    public BooleanTable()
        setDefaultCloseOperation( EXIT_ON_CLOSE );
        TableModel model = new AbstractTableModel()
            public String getColumnName(int column)
                return header[column].toString();
            public int getRowCount()
                return data.length;
            public int getColumnCount()
                return header.length;
            public Class getColumnClass(int columnIndex)
                return( data[0][columnIndex].getClass() );
            public Object getValueAt(int row, int col)
                return data[row][col];
            public boolean isCellEditable(int row, int column)
                return true;
            public void setValueAt(Object value, int row, int col)
                data[row][col] = value;
                fireTableCellUpdated(row, col);
        JTable table = new JTable(model);
        table.setDefaultRenderer( Boolean.class, new MyCellRenderer() );
        getContentPane().add( new JScrollPane( table ) );
        pack();
        setLocationRelativeTo( null );
        setVisible( true );
    public static void main( String[] a )
        try
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        catch( Exception e )
        new BooleanTable();
    private class MyCellRenderer extends JCheckBox implements TableCellRenderer
        public MyCellRenderer()
            super();
            setHorizontalAlignment(SwingConstants.CENTER);
        public Component getTableCellRendererComponent(JTable
                                                       table, Object value, boolean isSelected, boolean
                                                       hasFocus, int row, int column)
            if (isSelected) {
               setForeground(Color.white);
               setBackground(Color.black);
            } else {
               setForeground(Color.black);
               if (row % 2 == 0) {
                  setBackground(Color.white);
               } else {
                  setBackground(new Color(239, 245, 217));
            setSelected( Boolean.valueOf( value.toString() ).booleanValue() );
         return this;
}

Instead of extending JCheckBox, extend JPanel... put a checkbox in it. (border layout center).
Or better yet, don't extend any gui component. This keeps things very clean. Don't extend a gui component unless you have no other choice.
private class MyCellRenderer implements TableCellRenderer {
    private JPanel    _panel = null;
    private JCheckBox _checkBox = null;
    public MyCellRenderer() {
        //  Create & configure the gui components we need
        _panel = new JPanel( new BorderLayout() );
        _checkBox = new JCheckBox();
        _checkBox.setHorizontalAlignment( SwingConstants.CENTER );
        // Layout the gui
        _panel.add( _checkBox, BorderLayout.CENTER );
    public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column) {
        if( isSelected ) {
           _checkBox.setForeground(Color.white);
           _panel.setBackground(Color.black);
        } else {
           _checkBox.setForeground(Color.black);
           if( row % 2 == 0 ) {
              _panel.setBackground(Color.white);
           } else {
              _panel.setBackground(new Color(239, 245, 217));
        _checkBox.setSelected( Boolean.valueOf( value.toString() ).booleanValue() );
        return _panel;
}

Similar Messages

  • How 2 set the background color in j2me

    Can any body tell me how to set the background color to midlet.??

    if you are using Screen then you can call its setBackColor()
    or if you are using Canvas then you can call
    g.setColor(r,g,b);
    g.fillRect(0,0,getWidth,getHieght);
    where g is the Graphics instance of Canvas,for further information consult documentation

  • UITableView: set different background colors for header and the table

    I would like to set my background color for my UITableView to white and set my tableViewHeader backgroundColor to grayColor similar to the facebook app. When I bounce scroll my table so that you can see above the header, then currently it is white above the header view. I want that to be brown instead.
    In the facebook app, above the headerview, it is a blue color and below the table is a white color. If i try and set the UITableView backgroundColor to brown, then the top will be brown, but so will the bottom. Additionally, all of the unset cells will have a brown background instead of white.
    Any help with this?

    Fixed..

  • How to give Common Background color for all JPanels in My Swing application

    Hi All,
    I am developing a swing application using The Swing Application Framework(SAF)(JSR 296). I this application i have multiple JPanel's embedded in a JTabbedPane. In this way i have three JTabbedPane embedded in a JFrame.
    Now is there any way to set a common background color for the all the JPanel's available in the application??
    I have tried using UIManager.put("Panel.background",new Color.PINK);. But it did not work.
    Also let me know if SAF has some inbuilt method or way to do this.
    Your inputs are valuable.
    Thanks in Advance,
    Nishanth.C

    It is not the fault of NetBeans' GUI builder, JPanels are opaque by default, I mean whether you use Netbeans or not.Thank you!
    I stand corrected (which is short for +"I jumped red-eyed on my feet and rushed to create an SSCCE to demonstrate that JPanels are... mmm... oh well, they are opaque by default... ;-[]"+)
    NetBeans's definitely innocent then, and indeed using it would be an advantage (ctrl-click all JPanels in a form and edit the common opaque property to false) over manually coding
    To handle this it would be better idea to make a subclass of JPanel and override isOpaque() to return false. Then use this 'Trasparent Panel' for all the panels where ever transparency is required.I beg to differ. From a design standpoint, I'd find it terrible (in the pejorative sense of the word) to design a subclass to inconsistently override a getter whereas the standard API already exposes the property (both get and set) for what it's meant: specify whether the panel is opaque.
    Leveraging this subclass would mean changing all lines where a would-be-transparent JPanel is currently instantiated, and instantiate the subclass instead.
    If you're editing all such lines anyway, you might as well change the explicit new JPanel() for a call to a factory method createTransparentJPanel(); this latter could, at the programmer's discretion, implement transparency whichever way makes the programmer's life easier (subclass if he pleases, although that makes me shudder, or simply call thePanel.setOpaque(false) before returning the panel). That way the "transparency" code is centralized in a single easy to maintain location.
    I had to read the code for that latter's UI classes to find out the keys to use (+Panel.background+, Label.foreground, etc.), as I happened to not find this info in an authoritative document - I see that you seem to know thoses keys, may I ask you where you got them from?
    One of best utilities I got from this forum, written by camickr makes getting these keys and their values very easy. You can get it from his blog [(->link)|http://tips4java.wordpress.com/2008/10/09/uimanager-defaults/]
    Definitely. I bit a pair of knucles off when discovered it monthes after cumbersomely traversing the BasicL&F code...
    Still, it is a matter-of-fact approach (and this time I don't mean that to sound pejorative), that works if you can test the result for a given JDK version and L&F, but doesn't guarantee that these keys are there to stand - an observation, but not a specification.
    Thanks TBM for highlighting this blog entry, that's the best keys list device I have found so far, but the questions still holds as to what specifies the keys.
    Edited by: jduprez on Feb 15, 2010 10:07 AM

  • How to set a background color to view

    Hi All,
              i creared a view with 2 textboxes and a button.These elements are in TransparentContainer.I set the background color to the TransparentContainer.By setting color to the TransparentContainer it is comming at the center and the 4 sides of it is displaying in the normal background color of the browser
    i didnt find any color options for the view called RootUIElementContainer.the width and height of the view are setted to the browser means 1024*768.
    Just like sap editor which we get by the link https://www.sdn.sap.com i want to get my view .....
    I want to set color to this RootUIElementContainer element which effect the whole view...not the containers or groups which i add under this RootUIElementContainer
    Regards
    Padma N

    hi Padma,
    For changing the background colour you will have to make the change in the theme.
    You can download the theme editor plugin for eclipse from SDN. With this plugin, you can make changes to the default themes , save as a new theme
    Or if you are using portal, then goto system administrator, theme editor, select SAP Streamline and change the color in Screen areas -> application, then save the theme with different name.
    Best regards,
    Sangeeta

  • Set cell background color conditionally?

    I want to set a cells' background colors conditionally, e.g., if the computer value is between 5 to 9, make the background red. Is there any way to do that?

    That is a good question. It would appear it does not work. A way around it is to put 1:00 (1 hour duration, not 1 o'clock) in a cell and a 1:30 in another then reference those cells as your two conditions.
    This is not the only place where the duration format is not fully implemented.

  • How can I change background color for a text field

    Hi I tried this
    style="BACKGROUND-COLOR:#00FFFF"
    working fine in IE
    but not working in Netscape.. any other way to set the background color?

    Netscape 4.x does not support this feature. Only Netscape 6.x does.

  • How to set the Background Color of a Text Field in a Tabular Report.

    Hello,
    I tried to set the Background Color of a Text Field in a Tabular Report.
    But I was not able to change this colur.
    In the report attributes --> column attributes
    I tried already:
    1. Column Formating -- >CSS Style (bgcolor: red)
    2. Tabular Form Element --> Element Attributes (bgcolor: red)
    but nothing worked.
    Can anybody help me?
    I Use Oracle Apex 2.2.1 on 10gR2
    thank you in advance.
    Oliver

    in "Report Attributes" select the column to move to the "Column Attributes" page. In the "Element Attributes" field under the "Tabular Form Element" region enter
    style="background-color:red;"
    I will also check if there is a way to do this via the template and post here again
    edit:
    in your template definition, above the template, enter the following:
    < STYLE TYPE="text/css" >
    .class INPUT {background-color:red;}
    < /STYLE >
    (remove the spaces after the < and before the >)
    change "class" to the class that the template is calling
    (I'm using theme 9, the table has: class="t9GCCReportsStyle1" so I would enter t9GCCReportsStyle1)
    A side-effect of using this second version is that ALL input types will have a red background color--checkboxes, input boxes, etc.
    Message was edited by:
    TheJosh

  • How to retrieve default background color for JPanels or other containers?

    Hi everybody, I've written a small class extending the default JTextArea, intended to provide the functionality of a small, descriptive item in JPanels.
    import java.awt.*;
    import javax.swing.*;
    public class JInfoTextArea extends JTextArea{
         public JInfoTextArea(String text){
              super(text);
              setEditable(false);
              setFont(Font.decode("SansSerif"));
              setFocusable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
    //          setBackground(contentPane.getBackground());
              setAlignmentX(Component.LEFT_ALIGNMENT);
              setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    }As you can see, there formerly used to be a third parameter, namely contentPane, which contained a reference to the parent Container in order to set the TextArea's background color appropriately for transparency.
    Now, is there ANY way to retrieve the background color without either passing a dedicated parameter or doing something like
    setBackground((new JPanel()).getBackground());Any help is greatly appreciated!
    Yours, Stefanie

    To answer your original question the UIManager contains properties of the various components. In case your interested the following program has a fancy GUI display of all the components:
    http://www.discoverteenergy.com/files/ShowUIDefaults.java

  • How to change background color to JCheckBox in a JTable?

    Dear Friends,
    I have an JTable in my application. It has four columns. First, third and fourth column contains JCheckBox (JCheckBox is created using Boolean.class), secod column contains values.
    I have to change some of the cell color where JCheckBox is present.
    Could anyone please tell me how to change the color of the cell in the JTable?
    Thanks in advance,
    Sathish kumar D

    You would use a custom renderer.
    To get better help sooner, post a SSCCE that clearly demonstrates your problem.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    db
    Alternative link: SSCCE
    Edited by: Darryl.Burke

  • How to set disabled foreground color of JCheckBox?

    How do I set the disabled foreground color of JCheckBox? To clarify, I want to choose the color that is used to paint the component's foreground when it is disabled.
    thanks.

    Check out this thread:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=122112

  • How to change the background color for lookup column options in sharepoint 2007

    Hi,
    I have a custom List with 10 fields,and in the edit form we want to display only 6 fields,
    So I have customized it with sharepoint designer 2007 ,designed a new custom edit form(Insert->ShaerPoint Controls->Custom List Form)
    We are using IE8 Browser,and the site has JQuery 1.8 loaded .
    The lookup columns is getting rendered as textbox and dropdown arrow image,instead of select html element.
    When we click on arrow image,its displaying the values magically,So I am unable to highlight the options with text "ABC" in yellow background color
    basically in the input textbox its storing all the lookup values as "ID|value "in choices attribute (I saw this in browser dev tools)
    I tried to set the textbox color everytime it loses focus using blur,however its always returning the previous value instead of current selected value.
    Is there any way we can achieve this,Any solutions/thoughts
    Thanks everyone..

    hi i bet you need to amend your jquery script to get onclick values and put it with like append HTML if you want to use Jquery.
    Also did you know you could use javascript in calculated column with type number?
    Check:
    http://sharepointwijzer.nl/sharepoint-blog/tech/icc-html-calculated-column-sharepoint-view
    Imposible is nothing

  • How to set canvas extension color for arbitrary image rotation?

    I'm using Photoshop CS4 v 11.0 with Windows XP.  When adjusting canvas size there's a menu for chosing the canvas extension color.  Where is the menu for chosing canvas extension color for arbitrary image rotation?
    Thanks.

    This will be the background colour selected in your toolbox.

  • How to set image background color ?

    Hi All,
    In my project i have image,and if image have black spot or any unwanted spot then i will select that area and say clear it then it will remove that spot and set color of that area similar to area around that spot.
    I have written code for getting pixel color of selected area in image like this
    BufferedImage old_image = ImageIO.read(new File(myFile));
    int[] pixels = new_image.getRGB(0, 0,new_image.getWidth(), new_image.getHeight(),null, 0, new_image.getWidth());
    for (int i = 0; i < pixels.length; i++) {
    Color pixelColor = new Color(pixels);
    System.out.println("RGB ::"+pixelColor.getRGB());
    RGB returning negative value;
    Please tell me correct way how can i do this.
    It's very urgent.
    Thanks in advance.
    Thanks
    AP.

    i found the browser fill button.  Now how do I fill the browser fill with an image?

  • How to set the (specific) color for a Chart Series in a Flash Diagramm

    Hello all,
    I wonder how I can set the color (of a bar) for a Chart Series in a Flash Diagramm.
    So far I found now set-screw for this.
    Can someone give me a hint please.
    Thanks in advance.
    Andre

    Hi,
    On the Chart Attributes page for the region, change the "Color Scheme" setting to Custom. Then, in the "Custom Colors" setting, enter the colours you want for all series, separated by a comma. For example:
    red,yellow,greenAndy

Maybe you are looking for

  • Where are my albums?

    Upgraded to this new mac software and had problems with iPhoto. Didn't support my printer so had to buy a new one (not impressed). Husband had trouble getting iPhoto to work/print and had to reload library but now this new iPhoto (which i don't like

  • Need help in creating multiple signature forms?

    need help in creating multiple signature forms that can be digitally signed in adobe reader

  • Adobe PDF Printing Preferences (Version Adobe Acrobat 9)

    Is it possible to specify the output PDF filename like "abc.pdf" in Adobe PDF Settings? Thanks you for answer this dummy question.

  • Count the number of elements in an Arraylist

    My arraylist has these elements inside it. [house,tom:, agent,, person,, untidy,jack:, ordered,, tidy,, tiled,roof,tom:, agent,, person,,.....]. The list continues like this. How can I count the number of elements after each tom upto before each jack

  • Unable to update Policies in Policy Manager

    After I make some modification to a policy and click submit/save, it keeps loading. If I click on some link and come back to that policy, I see the changes have been done. But the changes does not takes effect without restarting the Policy Manager an