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

Similar Messages

  • 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 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;
    }

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

  • Background image  for JPanel using UI Properties

    Is there any way to add background image for JPanel using UI Properties,
    code is
    if (property.equals("img")) {
    System.out.println("call image file in css"+comp);
    //set the background color for Jpanel
    comp.setBackground(Color.decode("#db7093"));
    here the comp is JPanel and we are setting the background color,
    Is there any way to put the Background image for the JPanel ????

    KrishnaveniB wrote:
    Is there any way to put the Background image for the JPanel ????Override the paintComponent(...) method of JPanel.
    e.g.
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import javax.imageio.ImageIO;
    public class ImagePanel {
        public void createAndShowUI() {
            try {
                JFrame frame = new JFrame("Background Image Demo");
                final Image image = ImageIO.read(new File("/home/oje/Desktop/icons/yannix.gif"));
                JPanel panel = new JPanel() {
                    protected void paintComponent(Graphics g) {
                        g.drawImage(image, 0, 0, null);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(new Dimension(400, 400));
                frame.setContentPane(panel);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            } catch (IOException ex) {
                ex.printStackTrace();
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new ImagePanel().createAndShowUI();
    }

  • Setting a default background color

    Hi All,
    I would like to set a default background color for all the
    components that I'm going to draw. What is the best
    way to achieve this?
    Thanks.
    Syed

    You can set using UIManager of the Look and Feel.
    UIManger.put("Button.background", Color.blue);
    will set the color of all the JButtons to blue. Like that you can change for all the components you need.
    Mohan

  • How can I add background color to NSView?

    In NSView how can I add a background color?

    A Google search for nsview background color turned up many results, including the following Stack Overflow questions:
    Setting the background color of an NSView
    Best way to change the background color for an NSView

  • How to set background color for selected days in DateChooser

    How to set background color for selected days. I created
    checkbox for each day [Son,Mon,Tue,Wed,Thu,Fri,Sat] and a
    DateChooser, I want to change the background color for the selected
    day when i click on a button after selecting the desired checkboxs
    [ monthly wise/yearly wise]
    Thanks in advance

    There is no button involved in the following code, but it may
    be of use to you:
    <?xml version="1.0"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    creationComplete="init()">
    <mx:Script>
    <![CDATA[
    private var origColor:uint;
    private function init():void {
    origColor = dc.getStyle("selectionColor");
    public function setBackGrdColors(newColor:uint):void {
    dc.setStyle("selectionColor", origColor);
    if(dc.selectedDate){
    var dayOfWeek:Number = dc.selectedDate.day;
    else{
    return;
    switch(dayOfWeek) {
    case 0:
    if(sun.selected)
    dc.setStyle("selectionColor", newColor);
    break;
    case 1:
    if(mon.selected)
    dc.setStyle("selectionColor", newColor);
    break;
    case 2:
    if(tue.selected)
    dc.setStyle("selectionColor", newColor);
    break;
    case 3:
    if(wed.selected)
    dc.setStyle("selectionColor", newColor);
    break;
    case 4:
    if(thu.selected)
    dc.setStyle("selectionColor", newColor);
    break;
    case 5:
    if(fri.selected)
    dc.setStyle("selectionColor", newColor);
    break;
    case 6:
    if(sat.selected)
    dc.setStyle("selectionColor", newColor);
    break;
    default:
    break;
    ]]>
    </mx:Script>
    <mx:VBox horizontalAlign="center" verticalGap="20">
    <mx:DateChooser id="dc" textAlign="left"
    change="setBackGrdColors(cellColor.selectedColor)"/>
    <mx:HBox width="100%" horizontalAlign="center">
    <mx:CheckBox id="sun" label="Sun"/>
    <mx:CheckBox id="mon" label="Mon"/>
    <mx:CheckBox id="tue" label="Tue"/>
    <mx:CheckBox id="wed" label="Wed"/>
    </mx:HBox>
    <mx:HBox width="100%" horizontalAlign="center">
    <mx:CheckBox id="thu" label="Thu"/>
    <mx:CheckBox id="fri" label="Fri"/>
    <mx:CheckBox id="sat" label="Sat"/>
    </mx:HBox>
    <mx:HBox width="300" horizontalAlign="center">
    <mx:Label text="Background Color" />
    <mx:ColorPicker id="cellColor"
    selectedColor="#FF00FF"/>
    </mx:HBox>
    </mx:VBox>
    </mx:Application>

  • How can i use this color for my Application Background ?? Screen Shot Attached

    Hi ,
    I can find only plain colors on to Color Picker , but this is line mixed color
    How can use this attached Color for my Applications Background Color .
    Please find the Screen Shot attached .
    please see the background  color

    Are you trying to apply a gradient background?
    In Flex 3 in Application tag:
    <?xml version="1.0"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
      backgroundColor="#666666"
      backgroundGradientColors="[#333333, #666666]">
    </mx:Application>
    In Flex 4 you need to set the backgroundColor and apply a skin for the gradient:
    -------------- mySkins/MyAppSkin.mxml -------------
    <?xml version="1.0" encoding="utf-8"?>
    <!-- containers\application\mySkins\MyAppSkin.mxml -->
    <s:Skin xmlns:fx="http://ns.adobe.com/mxml/2009"
            xmlns:mx="library://ns.adobe.com/flex/mx"
            xmlns:s="library://ns.adobe.com/flex/spark">
      <fx:Metadata>
        [HostComponent("spark.components.Application")]
      </fx:Metadata>
      <s:states>
        <s:State name="normal" />
        <s:State name="disabled" />
      </s:states>
      <!-- fill -->
      <s:Rect id="backgroundRect" left="0" right="0" top="0" bottom="0">
        <s:fill>
          <s:LinearGradient rotation="90">
            <s:entries>
              <s:GradientEntry color="0x333333" ratio="0" alpha="1"/>
              <s:GradientEntry color="0x666666" ratio=".66" alpha="1"/>
            </s:entries>
          </s:LinearGradient>      
        </s:fill>
      </s:Rect>
      <s:Group id="contentGroup" left="10" right="10" top="10" bottom="10">
        <s:layout>
          <s:VerticalLayout/>
        </s:layout>
      </s:Group> 
    </s:Skin>
    -------------- test.mxml -------------
    <?xml version="1.0"?>
    <!-- controls\button\PopUpButtonMenu.mxml -->
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx"
                   height="100%" width="100%">
      <s:SkinnableContainer skinClass="mySkins.MyAppSkin"
        width="100%" height="100%"/>
    </s:Application>
    If this post answers your question or helps, please mark it as such. Thanks!
    http://www.chikaradev.com
    Adobe Flex Development and Support Services

  • Simple/silly question: how do I set/change default font/color for outgoing mail messages?

    Simple/silly question: how do I set/change default font/color for outgoing mail messages?

    Just a suggestion..........
    Download Thunderbird.  Easier to use when it comes to what you want to do w/your emails. 

  • How to change the background color only for one HTML-Portlet?

    Hi all,
    I have created a HTML-Portlet in my root-page. The root page have a style: Main-Style.
    I want to change the background-color only for this one HTML-Portlet:
    <html>
    <header><title>Test</title></header>
    <body bgcolor="#999999">
    Test
    </body>
    </html>
    But this does not work...
    When I use the CSS, then it will change the background-color for the root-page too.
    Thans
    Leonid Pavlov

    could you try this
    <table bgcolor="#999999">
    <tr>
    <td>
    test
    </td>
    </tr>
    </table>
    I don't think you need <html><header><title>Test</title></header>
    <body></body></html> for your HTML-Portlet.

  • Set property for  background color for JButton

    I am attempting to change the colors of the UI for JButton. The change does not appear to be taking. The reason appears to be that JButton, and for that matter JLabel setOpaque(false); How can I globally change this to setOpaque(true);
    Second is there a way to save the default property hash table after the changes are made so that it will run the next time the program is executed.

    Thank you for responding. I don't feel that I have been clear in the statement of the problem. I have written a medium size desktop application(20,000 statements). I am trying to customize the color scheme by modifying the default laf properties color entries. I can modify JPanel through a put to the properties hash table. When I attempt to change the background color for JLabel and JButton it doesn't seem to take. I believe that the reason it doesn't take is because opaque(false). Is there a property that allows the overide of opaque to true or do I have to change all of the numerous JButtons in my program.
    I have decided to store all changes in a file and make the changes at the point that the program initializes each time its run.
    I am not looking for specific code but an approach.
    I would appreciate your advice.

  • How to change the background color of a desktop??

    any ideas how to change the background color of a desktop?? Now the default color is blue. I couldn't fine the API in JDesktopPane on doing that..
    JDesktopPane desktop = new JDesktopPane(); //(textArea);

    Try the method setBackground. For me it's work.

  • Flex 4.5.1 SDK & default-background-color Compiler Argument

    Hey guys,
    I was scanning the available compiler arguments list (http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf69084-7a92.html) for Flex 4.5 SDK and noticed that the -default-background-color argument is gone (I realize it's been gone since 4 just haven't used the SDK much lately).  My background shows up as black when I run my app (it's an AS3 app with the new Away3D 4.0 Broomstick library) and there is no Flex code in my app so I was depending on this compiler argument to set my background color to white.
    How can I achieve this now that the argument is no longer available?  I just simply want to have a white background without physically having to create a white sprite in the back of my scene.  Is this possible anymore?
    Matt

    Simeon,
    Thanks for that, I had a brainfart and forgot you can have the properties defined in that manner.  I changed it but it still wasn't working which made me realize I had to change the backgroundColor property on the view in Away3D.  I realized this after trying the params for the class and then not adding the view (which had a white bg) and then i looked at the docs and bam, there it was.  Thanks!
    Matt

Maybe you are looking for

  • Hard crashes AND app crashes (with Console logs)

    This topic is several months, if not a couple of years, in the making. I bought two white MBs in July of 07 from the refurbished section of the Apple Store. My wife's needed a trip to the Apple Care depot not long ago, and I'm starting to think mine

  • GR55 Cost center report?

    Dear Friends, Pls explain me what is GR55 cost center report and guide me Pls.... New GR55 Cost center report Could you create a new GR55 report based on the existing report GR55   ZAIQ for Holts UK (Co code EUK1) to include the accounts highlighted

  • Error connecting to CLOUDSCAPE database from EJB

    Hi All, I am working on Sun's reference implementation App Server verson 1.3.1. It comes shipped with cloudscape database. When I write try to connect to this App Server through JSP that calls methods through Enterprise Java Beans I get this Error Me

  • Iphone crashing apps

    Hi all can someone help me find the problem in that log?  http://pastebin.com/5hNqnVTw   ty

  • Double Boxes and OTS Boxes

    Is it possible to do a double box effect or an over the shoulder box effect like you see in newscasts? I know normally this is done live usually but I was curious if this is possible in post