JButton Background in 1.4.2

Anyone else noticed that when you set the background of a JButton with Java version 1.4.2 and the L&F of Windows (now XP look and feel) that only the edges of the buttons background are colored? This seems like a bug to me. Is there a way to work around this in version 1.4.2 besides rapidly retreating back to 1.4.1 software?

Regarding bug report 4880747:
Since certain accusations about "this individual" and the rest of the Swing Team have
now been brought to the public, it gives me a good opportunity to explain (yet again)
how the Swing XP L&F works. I've had everybody in the team involved with trying to
figure out what it is that we're being asked to do, but we are still at a loss and
would be very grateful for more constructive suggestions.
1. The Swing Windows XP L&F uses the operating system mechanism for painting buttons.
We do not have any code whatsoever to generate rounded shapes for buttons. It is
all defined in the Luna style - which just happens to be the default theme for XP.
The user has full control in choosing the ui appearance in the Windows Desktop
Properties dialog. If there is anything in a Swing window that doesn't react the
same way to changes as a native app does, then it's due to a bug and we'll be glad to
try to fix it. Hopefully, our so called "XP" L&F will survive into the Longhorn
releases, even if MS should decide to make buttons be triangular or whatever.
2. We have been told repeatedly that native Windows apps can have real Luna buttons
(rounded, with specular highlights) and still allow the developer to change the
button background. Yet we have still not seen any examples of such code or screen
shots thereof.
3. If anybody wants to write their own L&F, there are many ways to do it. The
simplest way to draw your own buttons is to either override paintComponent(), or at
least to to turn off the UI painting by calling setContentAreaFilled(false) followed
by setOpaque(true). If the XP L&F is causing conflicts with old code that assumed a
certain implementation of the Classic Windows L&F, then just set the system property
"swing.noxp". For 1.5 we are planning to add a new UI class which can be used to
switch to the classic L&F at runtime. It will probbably be called
com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel.
Cheers,
Leif Samuelsson
Java Swing Team
Sun Microsystems, Inc.

Similar Messages

  • Why does JButton background color change when  clicking ?

    Hello,
    I have defined :
    JButton mybutton = new JButton(Icon xxx) ;
    with no associated text and I set both foreground and background colors to black, and an empty border.
    This is because the background color of the container which contents this button is also black and I want to see only the button icon.
    When I click on the icon , the button background color becomes grey. How can I change this to make it remains black ?
    Thanks a lot.
    Gege

    Well, the color changes because that is how the look and feel is defined,
    presumably to give better feedback to the user that she has clicked the
    button.
    If you don't want this, you could try using a different L&F which doesn't do this.
    Alternatively, If you've only got the one button, you could just do
        UIManager.put( "Button.select", Color.BLACK );If you have multiple buttons, and you want the other buttons to behave
    normally, you can extend the one button and have it change the color
    while it is pressed, e.g.,
    import java.awt.*;
    import java.io.IOException;
    import java.net.URL;
    import javax.swing.*;
    public class ButtonSelect extends JFrame {
         public ButtonSelect() throws IOException {
              super();
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel panel = new JPanel();
              panel.add( new JButton( "Normal" ) );
              Image img = Toolkit.getDefaultToolkit().getImage( new URL("http://www.google.com/intl/en/images/logo.gif" ) );
              ImageIcon ii = new ImageIcon( img );
              JButton b = new JButton( ii ) {
                   static final private String KEY = "Button.select";
                   public void paint( Graphics g ) {
                        Color save = null;
                        if ( getModel().isArmed() && getModel().isPressed() ) {
                             save = UIManager.getColor( KEY );
                             UIManager.put( KEY, Color.WHITE );
                        super.paint( g );
                        if ( save != null )
                             UIManager.put( KEY, save );
              b.setForeground( Color.WHITE );
              b.setBackground( Color.WHITE );
              b.setFocusPainted( false );
              panel.add( b );
              getContentPane().add( panel );
              pack();
              setVisible( true );
         public static void main( String[] a ) throws IOException {
              new ButtonSelect();
    }

  • JButton background color on XP difference with theme classic and XP

    Hi all,
    I got a problem on Windows XP JSE 1.5.0_01 when trying to set the
    background of a JButton (or to be more precise of a subclass of
    JButton, but no override of paint or paint Component).
    The button background behaviour is correct with the theme Windows
    classic but not with XP Windows one. In the later case, only the
    background below the button is coloured, the rest is grey: impossible
    to modify the colour of the button itself.
    Any idea?
    F.

    It did.
    Thanx a lot.
    F.
    Maybe this thread will help you:
    http://forum.java.sun.com/thread.jspa?forumID=57&threa
    dID=430926

  • JButton background color question

    Hi everybody,
    I have a feeling I'm going to get slammed for this, but I have to ask a very general question and hope for an answer.
    I have a JDialog on which buttons don't seem to hold their background color. That is, when I use setBackground, the only color change I get is a very thin outline of the color, and the rest of the button is white. The strange thing about the button is that the white center actually seems transparent--if I change the panel the button is on to another color besides white, the center of the button turns that color.
    I've tried to solve this problem with setOpaque( true ), setContentAreaFilled( true ), setBackground( color ), setForeground( color ), and I'm pretty sure every combination of those.
    Unfortunately, I haven't been able to reproduce this in a test case, so I can't give a SSCCE, although I've tried for a while now to make one.
    So...has anyone ever run into a problem like this and can give me some advice? I'm sorry I can't be more specific, if anyone has a question I'll do my best to answer.
    Thanks,
    Jezzica85

    I have a feeling I'm going to get slammed for this, but I have to ask a very general question and hope for an answer.Why would people be harsh on you? The only risk you take is: vague question => vague answer (or random).
    So...has anyone ever run into a problem like this and can give me some advice? I'm sorry I can't be more specific, if anyone has a question I'll do my best to answer.Never seen that myself, so I'll add a few random questions/thoughts:
    I have a JDialog on which buttons don't seem to hold their background color. That is, when I use setBackground, the only color change I get is a very thin outline of the color, and the rest of the button is white.- are you using a custom JButton subclass? If yes are you certain the subclass does not override paintComponent()?
    - If not, the button is painted by its ButtonUI. Can you tell which UI class is used (sysout(+theButton.getUI()+)?
    The UI is set according to the LookAndFeel.
    - Do you set any special LookAndFeel (+UIManager.setLookAndFeel(...)+, or look and feel's UIDefault properties in your app (generally that is done at startup)?
    - If not, can you tell the current look and feel when you bring up the dialog (+UIManager.getLookAndFeel(...)+, although that can be inferred from the ButtonUI subclass' name.
    I've tried to solve this problem with setOpaque( true ), setContentAreaFilled( true ), setBackground( color ), setForeground( color ), and I'm pretty sure every combination of those.FYI, the ButtonUI paints the button however it sees fit; in particular it doesn't have to respect the colors, opacity, filling... properties.
    Eventually:
    - are you using a custom JDialog subclass (probably, as that's generally how people write dialogs; not the best way IMHO, but there are cases where this is hard to avoid).
    I see you can't provide an SSCCE right ow, but maybe you can try to narrow the list of suspects in your side?
    - Do you reproduce the same problem at startup, if you bring the JDialog up as soon as possible?
    - Do you reproduce the problem with a mere JOPtionpane.showMessageDialog(..., theButton,...)?
    - Do you reproduce the problem outside of the JDialog context (I see you mention using a different JPanel, but is that in the dialog or somewhere else?
    Good luck with your investigations.
    Edited by: jduprez on Sep 30, 2009 8:20 AM

  • JButton background turns grey when clicked

    Hi,
    I have a JButton that I have customised by setting the background colour to beige and hiding the border using setBorderPainted(false). I have also got rid of the outline that normally appears when you click it using setFocusPainted(false).
    My problem is that when I run my applet in a browser and I click on a button, the background flashes grey while I'm clicking. This only happens in the browser - when I run it in JBuilder there is no problem. Can you help?
    Thanks!
    David

    Unfortunately, this is a consequence of having the UI logic separated from the button component. In order to change the button's selected/pressed color, you have three options:
    1) set the UI to your own custom UI (see http://java.sun.com/products/jfc/tsc/articles/sce/). You don't have to implement a whole new UI, but you'll still have work cut out for you if you're not familiar with this.
    2) change the color for ALL the buttons in the application usingUIManager.set("Button.select", new javax.swing.plaf.ColorUIResource(0,0,0)); Obviously, you should specify a good color.
    3) create a subclass of JButton, call setContentAreaFilled(false); on it, and paint it yourself.

  • JButton Background Color difference Windows/Solaris

    I have a GUI application that has several JButtons, and the program sets them to different colors based on data received from a network. The program was developed on Solaris, and the GUI has several users. We used setBackground(Color.XXX) to set the Colors. We have users that use the GUI on windows. On Solaris, the entire JButton becomes the desired color. On Windows, the JButton is gray, and only the outline of the button is in the desired color. Is there anyway to configure the Runtime Environment on Windows so that the entire button is the desired color. If not, what other options are there?
    Thank You in Advance for Your Help!!!

    I followed these threads and none of these solutions created the LAF I am after. What I ended up doing is creating my own "button" by extending JPanel. This has a consistent look across all LAF's & OS's I've tried it on. I just override mouseClicked to get the button specific behaviour that I need.
    private class MyButton extends JPanel implements MouseListener
    public MyButton(Color color)
    setBorder(BorderFactory.createRaisedBevelBorder());
    setBackground(color);
    addMouseListener(this);
    public void mouseClicked(MouseEvent e)
    public void mousePressed(MouseEvent e)
    setBorder(BorderFactory.createLoweredBevelBorder());
    public void mouseReleased(MouseEvent e)
    setBorder(BorderFactory.createRaisedBevelBorder());
    public void mouseEntered(MouseEvent e)
    public void mouseExited(MouseEvent e)
    }

  • How to get a colored JButton?

    I wanted to have a coloured button, I set the background of the JButton to the desired color, but when I set the desired look n feel to the one of the system, like Windows Xp Look n feel, i could only see the border of the button with that color and not the whole button having that color. How can I get the color on the button, plz suggest.
    Thanks.

    Use the search file (on the left) and search the forum using "px jbutton background" for other postings on this topic.

  • Problem With ButtonUI in an Auxiliary Look and Feel

    This is my first post to one of these forums, so I hope everything works correctly.
    I have been trying to get an axiliary look and feel installed to do some minor tweaking to the default UI. In particular, I need it to work with Windows and/or Metal as the default UI. For the most part I let the installed default look and feel handle things with my code making some colors lighter, darker, etc. I also play with focus issues by adding FocusListeners to some components. I expect my code to work reasonably well no matter what the default look and feel is. It works well with Motif, Metal, and Windows, the only default look and feels I've tested with. What I'm going to post is a stripped down version of what I have been working on. This example makes gross changes to the JButton background and foreground colors in order to illustrate what I've encountered.
    I have three source code files. The first, Problem.java, creates a JFrame and adds five buttons to it. One button installs MyAuxLookAndFeel as an auxiliary look and feel using MyAuxButtonUI for the look and feel of JButtons. The next button removes that look and feel. The next button does nothing except print a line to System.out. The next button installs MyAuxLookAndFeel as an auxiliary look and feel using MyModButtonUI for the look and feel of JButtons. The last button removes that look and feel.
    The problem is, when I install the first auxiliary look and feel, buttons are no longer tabable. Also, they cannot be invoked by pressing the space button when they're in focus. When I remove the first auxiliary look and feel everything reverts to behaving normally. When I add the "Mod" version, button tabability is fine. The only difference is I've added the following code:
    if ( c.isFocusable() ) {
       c.setFocusable(true);
    }That strikes me as an odd piece of code to profoundly change the program behavior. Anyway, after adding and removing the "Mod" look and feel, the tababilty is forever fixed. That is, if I subsequently re-install the first look and feel, tababilty works just fine.
    The problem with using the space bar to select a focused button is more problematic. My class is not supposed to mess with the default look and feel which may or may not use the space bar to press the button with focus. When the commented code in MyModButtonUI is uncommented, things behave correctly. Even the statement
    button.getInputMap().remove( spaceKeyStroke );doesn't mess things up after the auxiliary look and feel is removed. So far I've tested this with JRE 1.4.2_06 under Windows 2000, JRE 1.4.2_10 under Windows XP, and JRE 1.5.0_06 under Windows XP and the behavior is the same.
    All of this leads me to two questions.
    1. Is my approach fundamentally flawed? I've extended TextUI and ScrollBarUI with no problems. This is the only problem I've encountered with ButtonUI. My real workaround for the space bar issue is better than the one I've supplied in the example, but it certainly is not guaranteed to work for any arbitrary default look and feel.
    2. Assuming I have no fundamental problems with my approach, it's possible I've found a real bug. I searched the bug database and couldn't find anything like this. Of course, this is the first time I've tried seasrching the database for a bug so my I'm doing it badly. Has this already been reported as a bug? Is there any reason I shouldn't report it?
    What follows is the source code for my example. It's in three files because the two ButtonUI classes must be public in order to work. Thanks for insight you can provide.
    Bill
    File Problem.java:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Problem extends JFrame {
       public boolean isAuxInstalled = false;
       public boolean isModInstalled = false;
       public LookAndFeel lookAndFeel = new MyAuxLookAndFeel();
       private static int ctr = 0;
       public static void main( String[] args ) {
          new Problem();
       public Problem() {
          this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setSize(250, 150);
          setTitle("Button Test");
          JButton install = new JButton("Install");
          JButton remove = new JButton("Remove");
          JButton doNothing = new JButton("Do Nothing");
          JButton installMod = new JButton("Install Mod");
          JButton removeMod = new JButton("Remove Mod");
          this.getContentPane().setLayout(new FlowLayout());
          this.getContentPane().add(install);
          this.getContentPane().add(remove);
          this.getContentPane().add(doNothing);
          this.getContentPane().add(installMod);
          this.getContentPane().add(removeMod);
          install.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                if ( !isAuxInstalled ) {
                   isAuxInstalled = true;
                   UIManager.addAuxiliaryLookAndFeel( lookAndFeel );
                   SwingUtilities.updateComponentTreeUI( Problem.this );
          remove.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                if ( isAuxInstalled ) {
                   isAuxInstalled = false;
                   UIManager.removeAuxiliaryLookAndFeel( lookAndFeel );
                   SwingUtilities.updateComponentTreeUI( Problem.this );
          doNothing.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                System.out.println( "Do nothing " + (++ctr) );
          installMod.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                if ( !isModInstalled ) {
                   isModInstalled = true;
                   UIManager.addAuxiliaryLookAndFeel( lookAndFeel );
                   SwingUtilities.updateComponentTreeUI( Problem.this );
          removeMod.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                if ( isModInstalled ) {
                   isModInstalled = false;
                   UIManager.removeAuxiliaryLookAndFeel( lookAndFeel );
                   SwingUtilities.updateComponentTreeUI( Problem.this );
          setVisible(true);
       class MyAuxLookAndFeel extends LookAndFeel {
          public String getName() {
             return "Button Test";
          public String getID() {
             return "Not well known";
          public String getDescription() {
             return "Button Test Look and Feel";
          public boolean isSupportedLookAndFeel() {
             return true;
          public boolean isNativeLookAndFeel() {
             return false;
          public UIDefaults getDefaults() {
             UIDefaults table = new MyDefaults();
             Object[] uiDefaults = {
                "ButtonUI", (isModInstalled ? "MyModButtonUI" : "MyAuxButtonUI"),
             table.putDefaults(uiDefaults);
             return table;
       class MyDefaults extends UIDefaults {
          protected void getUIError(String msg) {
    //         System.err.println("(Not) An annoying error message!");
    }File MyAuxButtonUI.java:
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.plaf.*;
    import javax.swing.plaf.multi.*;
    import javax.accessibility.*;
    public class MyAuxButtonUI extends ButtonUI {
       private Color background;
       private Color foreground;
       private ButtonUI ui = null;
       public static ComponentUI createUI( JComponent c ) {
          return new MyAuxButtonUI();
       public void installUI(JComponent c) {
          MultiButtonUI multiButtonUI = (MultiButtonUI) UIManager.getUI(c);
          this.ui = (ButtonUI) (multiButtonUI.getUIs()[0]);
          super.installUI( c );
          background = c.getBackground();
          foreground = c.getForeground();
          c.setBackground(Color.GREEN);
          c.setForeground(Color.RED);
       public void uninstallUI(JComponent c) {
          super.uninstallUI( c );
          c.setBackground(background);
          c.setForeground(foreground);
          this.ui = null;
       public void paint(Graphics g, JComponent c) {
          this.ui.paint( g, c );
       public void update(Graphics g, JComponent c) {
          this.ui.update( g, c );
       public Dimension getPreferredSize(JComponent c) {
          if ( this.ui == null ) {
             return super.getPreferredSize( c );
          return this.ui.getPreferredSize( c );
       public Dimension getMinimumSize(JComponent c) {
          if ( this.ui == null ) {
             return super.getMinimumSize( c );
          return this.ui.getMinimumSize( c );
       public Dimension getMaximumSize(JComponent c) {
          if ( this.ui == null ) {
             return super.getMaximumSize( c );
          return this.ui.getMaximumSize( c );
       public boolean contains(JComponent c, int x, int y) {
          if ( this.ui == null ) {
             return super.contains( c, x, y );
          return this.ui.contains( c, x, y );
       public int getAccessibleChildrenCount(JComponent c) {
          if ( this.ui == null ) {
             return super.getAccessibleChildrenCount( c );
          return this.ui.getAccessibleChildrenCount( c );
       public Accessible getAccessibleChild(JComponent c, int ii) {
          if ( this.ui == null ) {
             return super.getAccessibleChild( c, ii );
          return this.ui.getAccessibleChild( c, ii );
    }File MyModButtonUI.java:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.plaf.*;
    public class MyModButtonUI extends MyAuxButtonUI
       static KeyStroke spaceKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0 );
       public static ComponentUI createUI( JComponent c ) {
          return new MyModButtonUI();
       public void installUI(JComponent c) {
          super.installUI(c);
          c.setBackground(Color.CYAN);
          if ( c.isFocusable() ) {
             c.setFocusable(true);
    //      final JButton button = (JButton) c;
    //      button.getInputMap().put( spaceKeyStroke, "buttonexample.pressed" );
    //      button.getActionMap().put( "buttonexample.pressed", new AbstractAction() {
    //         public void actionPerformed(ActionEvent e) {
    //            button.doClick();
    //   public void uninstallUI(JComponent c) {
    //      super.uninstallUI(c);
    //      JButton button = (JButton) c;
    //      button.getInputMap().remove( spaceKeyStroke );
    //      button.getActionMap().remove( "buttonexample.pressed" );
    }

    here is the code used to change the current look and feel :
    try {
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
             catch (InstantiationException e)
                  System.out.println("Error occured  "+ e.toString());
             catch (ClassNotFoundException e)
                  System.out.println("Error occured  "+ e.toString());
             catch (UnsupportedLookAndFeelException e)
                  System.out.println("Error occured  "+ e.toString());
             catch (IllegalAccessException e)
                  System.out.println("Error occured in .. " + e.toString());
             Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
             Fenetre fen = new Fenetre();
             fen.setSize(dim.width, dim.height);
             fen.setResizable(false);
                 fen.setLocation(0, 0);
                  fen.setVisible(true);

  • How to get default color of a selected row in a JLIst

    I have a JList that I am changing the font color for based on a certian situation so I created my own MyCellRenderer to do this. However, when I select an item in the list the row is no longer highlighted. I used the isSelected method to determine if a row was selected and then change the background color of that row. However, I would like the color to be the default color that you get when you select a row in a default JList. I can't seem to figure out how to get that color. How do I obtain what that color is? I found an example where you can get the default color for the background of a button and use that color so I would guess it is something similar to that. My code is below so I hope someone can tell me how to get that color that I want.
    Thanks...Chris
    class MyCellRenderer extends JLabel implements ListCellRenderer {
         public MyCellRenderer() {
              setOpaque(true);
         public Component getListCellRendererComponent(
             JList list,
             Object value,
             int index,
             boolean isSelected,
             boolean cellHasFocus)
             int index1 = value.toString().indexOf("-");
               String errors = value.toString().substring(index1 + 1, index1 + 6).trim();
             int numErrors = Integer.parseInt(errors);
               if (numErrors > 0)
                      setForeground(Color.red);
                      setBackground(Color.white);          
             else
                  setBackground(Color.white);
                  setForeground(Color.black);
             if(isSelected)
                  //ColorUIResource col = (ColorUIResource)UIManager.getDefaults().get("JButton.background");
                  ColorUIResource col = (ColorUIResource)UIManager.getDefaults().get("Button.background");
                  setBackground(col);
             setText(value.toString());
             return this;
    }

    Swing related questions should be posted in the Swing forum.
    I would like the color to be the default color that you get when you select a row in a default JList. I can't seem to figure out how to get that colorlist.getSelectionBackground();

  • Change colors to all components in a consistent way

    Is there a way to change color to all components of an application (or of a JFrame), such as all JButtons backgrounds, JFrame backgrounds etc.?
    I suppose i've to deal with UIManager defaults, but is there some facility, or some check-list to help achieve this task?.
    Thanks in advance
    Agostino

    Check out my ComponentMapper class. You could do it with this by running the mapper on the contentpane (and potentially the JMenuBar too if you like)
    You are welcome to use and modify this code but please don't change the package or take credit for it as your own work
    tjacobs.util.ComponentMapper
    ======================
    package tjacobs.util;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.TextComponent;
    import javax.swing.JFileChooser;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.text.JTextComponent;
    public class ComponentMapper {
         public static interface MappedFunc {
              public void func(Component c);
         public static void map(Component c, MappedFunc func) {
              func.func(c);
              if (c instanceof Container) {
                   Container con = (Container)c;
                   int count = con.getComponentCount();
                   for (int i = 0; i < count; i++) {
                        map(con.getComponent(i), func);
         public static void main(String[] args) {
              JFileChooser fc = new JFileChooser();
              MappedFunc mf = new MappedFunc() {
                   public void func(Component c) {
                        if (c instanceof JTextComponent) {
                             System.out.println("found");
                             final JTextField tf = ((JTextField)c);
                             tf.setEditable(false);
                             tf.getDocument().addDocumentListener(new DocumentListener() {
                                  public void insertUpdate(DocumentEvent de) {
                                       Runnable r = new Runnable() {
                                            public void run() {
                                                 tf.setText("");
                                       SwingUtilities.invokeLater(r);
                                  public void removeUpdate(DocumentEvent de) {
                                  public void changedUpdate(DocumentEvent de) {
                             while (c != null) {
                                  System.out.println(c.getClass());
                                  c = c.getParent();
                             //disable the textfield
              map(fc, mf);
              fc.showSaveDialog(null);
    }

  • Muliple classes in applets

    am just starting to learn to use applets, and am a little confused with the structure. after imports, the applet generaly contines with pubic class xyz extend frame for example, which encomases most of the rest of the applet, so does that mean i can only use methords of xzy or can i put classes in side xzy.
    If you can understand what i mean, or can point me to an easy resourse on how i should structure, an applet and how i should layout different class's inside the applet i would be great full. Exaclty 5 duke doller greatfull (cos thats what i got left).

    Here's an example to illustrate.
    You can just as well put the two outer classes inside the applet. If you do then you won't need to pass a reference into the ControlPanel class to call methods in the DisplayPanel class. Instead you would put the DisplayPanel instance variable in class scope. In java:
    public class ExampleApplet extends JApplet
        DisplayPanel displayPanel;
        public void init()
            displayPanel = new DisplayPanel();
        class DisplayPanel...
        class ControlPanel extends JPanel
            JComboBox outerColor, innerColor;
            public ControlPanel(DisplayPanel dp)
                // create components for panel
        public static void main...
    }To call methods or get access to variables in another class you need a way to get a reference to that class.
    One benefit in keeping the classes separated is that you can isolate your event code, your drawing code and your gui display code. This can make it easier to conceptualize and maintain.
    /*  <applet code="ExampleApplet" width="400" height="400"></applet>
    *  use: >appletviewer ExampleApplet.java
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.Random;
    import javax.swing.*;
    public class ExampleApplet extends JApplet
        public void init()
            DisplayPanel displayPanel = new DisplayPanel();
            ControlPanel control = new ControlPanel(displayPanel);
            Container cp = getContentPane();
            cp.setLayout(new BorderLayout());
            cp.add(control, "North");
            cp.add(displayPanel);
         * Convenience method so you can run applet from command line
        public static void main(String[] args)
            JApplet applet = new ExampleApplet();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(applet);
            f.setSize(400,400);
            f.setLocation(200,200);
            applet.init();
            applet.start();
            f.setVisible(true);
    class DisplayPanel extends JPanel
        Random seed;
        Color bgColor, outerColor, innerColor;
        public DisplayPanel()
            seed = new Random();
            bgColor = Color.white;
            outerColor = Color.blue;
            innerColor = Color.orange;
            setBackground(bgColor);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth();
            int h = getHeight();
            int dia = Math.min(w, h)/4;
            g2.setPaint(outerColor);
            g2.fill(new Ellipse2D.Double(w/2 - dia/2, h/2 - dia/2, dia, dia));
            g2.setPaint(innerColor);
            g2.fill(new Ellipse2D.Double(w/2 - dia/4, h/2 - dia/4, dia/2, dia/2));
        public void setBackground()
            Color color = new Color(seed.nextInt(256), seed.nextInt(256), seed.nextInt(256));
            setBackground(color);
            repaint();
        public void setOuterColor(Color color)
            outerColor = color;
            repaint();
        public void setInnerColor(Color color)
            innerColor = color;
            repaint();
    class ControlPanel extends JPanel
        DisplayPanel displayPanel;
        JComboBox outerColor, innerColor;
        public ControlPanel(DisplayPanel dp)
            displayPanel = dp;
            // create components for panel
            JButton bgColor = new JButton("background");
            bgColor.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    displayPanel.setBackground();
            String[] outerColorNames = {
                "blue", "yellow", "cyan", "magenta"
            outerColor = new JComboBox(outerColorNames);
            String[] innerColorNames = {
                "orange", "red", "green", "pink"
            innerColor = new JComboBox(innerColorNames);
            ColorListener l = new ColorListener();
            outerColor.addActionListener(l);
            innerColor.addActionListener(l);
            // layout components
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1.0;
            add(bgColor, gbc);
            gbc.anchor = gbc.EAST;
            add(new JLabel("outer"), gbc);
            gbc.anchor = gbc.WEST;
            add(outerColor, gbc);
            gbc.anchor = gbc.EAST;
            add(new JLabel("inner"), gbc);
            gbc.anchor = gbc.WEST;
            add(innerColor, gbc);
        class ColorListener implements ActionListener
            Color[] outerColors = {
                Color.blue, Color.yellow, Color.cyan, Color.magenta
            Color[] innerColors = {
                Color.orange, Color.red, Color.green, Color.pink
            public void actionPerformed(ActionEvent e)
                JComboBox combo = (JComboBox)e.getSource();
                int index = combo.getSelectedIndex();
                if(combo == outerColor)
                    displayPanel.setOuterColor(outerColors[index]);
                if(combo == innerColor)
                    displayPanel.setInnerColor(innerColors[index]);
    }

  • Problem in setting background colour for jButton.

    Hi,
    I have a jButton in which I want to set the color of the body of the button to gray. But by setting the background color, the color of only the border surrounding the button is changed to red. How can I set the color of the the body of the button to gray?

    Maxideon wrote:
    Geeze. I never though it would be so hard to upload an image. It probably has to do with your location relative to where I uploaded (are you really in India?).Yes.
    Maybe those free hosting sights that show up in my google search are only US based.photobucket was the first result in my search, but I was surprised it isn't blocked ;-)
    I went ahead and created an account with photobucket. I'm assuming all I have to do is make the album public and provide a direct link (hopefully). Otherwise I just simply give up
    [Direct Link|http://i633.photobucket.com/albums/uu51/Maxideon/Button.png]
    [Share Link?|http://s633.photobucket.com/albums/uu51/Maxideon/?action=view&current=Button.png]
    Yup, I see it now. Tends to support what I said about system L&Fs (and you agreed)... I think if I was designing it, I would want to disallow even the red border :P
    Just a nitpick, but the whole purpose of the system L&Fs being to provide a user experience consistent with different OS'es, should one even be trying to change a button background? A splash of color can always be done with an Icon.I'm going to have to agree with you on this one.If the non-system look is absolutely necessary in a Vista L&F, a paintComponent override should be a solution. Or, in case multiple buttons are to be customized, a custom UI delegate inheriting from javax.swing.plaf.basic.BasicButtonUI.
    db

  • Problem in Setting Background Color for JButton

    Hi,
    I am using Background color for JButton (color is selected from the customized JColorChooser created by us) where it contains the option of transparency. If we choose light color, then the background is set to JButton, but when we mouse-over the JButton, other components inside the container (JPanel) is getting displayed inside the button.
    Can anyone help to sort out this problem.
    Thanks in advance.

    Hi,
    Here is the code.
    DialogWrapper is JDialog and ColorEditorPane is JPanel.
    DialogWrapper     dlg         = new DialogWrapper();
    ColorEditorPane colorPanel = new ColorEditorPane();
    colorPanel.setValue( _data.getTransparentColor());
    dlg.showWrappedDialog( colorPanel, "color_help", "color_dialog" );
    if( dlg.isOK())
    Color chosenColor = (Color) colorPanel.getValue().getContent();
    _data.setTransparentColor( chosenColor );
    _transparentColorDisplay.setBackground( chosenColor );
    _transparentColorDisplay.setOpaque( true );
    this.repaint();
    this.doLayout();
    this.validate();
    }I've several components like JCheckBox, JRadioButton, JTextField in "this".

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

  • Background for JButton

    Hi all I am doing design a background for JButton and also doing design a metal look and place this as
    backgroung rather than using the plain colours eg black, red.
    I dont want to use setIcon because I would like to place an Icon on top eg an arrow for previous or next..
    Here is my sample code:
    import java.awt.*;
    import javax.swing.*;
    public class JImageButton extends JButton
    Image backgroundImage;
    public JImageButton()
    super();
    public JImageButton( Action a )
    super( a );
    public JImageButton( Icon icon )
    super( icon );
    public JImageButton( String text )
    super( text );
    public JImageButton( String text, Icon icon )
    super( text, icon );
    public void setBackgroundImage( Image image )
    MediaTracker mt = new MediaTracker( this );
    mt.addImage( image, 0 );
    try
    mt.waitForAll();
    backgroundImage = image;
    catch( InterruptedException x )
    System.err.println(
    "Specified background image could not be loaded." );
    public void paintComponent( Graphics g )
    super.paintComponent( g );
    Color saved = g.getColor();
    g.setColor( getBackground() );
    g.fillRect( 0, 0, getWidth(), getHeight() );
    g.setColor( saved );
    if( backgroundImage != null )
    int imageX = ( getWidth() - backgroundImage.getWidth( this ) ) / 2;
    int imageY = ( getHeight() - backgroundImage.getHeight( this ) ) / 2;
    g.drawImage( backgroundImage, imageX, imageY, this );
    if( !getText().equals( "" ) )
    g.drawString( super.getText(), getWidth() / 2, getHeight() / 2 );
    if( getIcon() != null )
    Icon icon = getIcon();
    icon.paintIcon( this, g, 10, 10 );
    public Dimension getpreferredSize()
    Dimension oldSize = super.getPreferredSize();
    Dimension newSize = new Dimension();
    Dimension returnSize = new Dimension();
    if( backgroundImage != null )
    newSize.width = backgroundImage.getWidth( this ) + 1;
    newSize.height = backgroundImage.getHeight( this ) + 1;
    if( oldSize.height > newSize.height )
    returnSize.height = oldSize.height;
    else
    returnSize.height = newSize.height;
    if( oldSize.width > newSize.width )
    returnSize.width = oldSize.width;
    else
    returnSize.width = newSize.width;
    return( returnSize );
    And here's a tester to show how it works...
    code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class JImageButtonTest extends JFrame
    JButton jb1, jb2;
    JImageButton jib1, jib2, jib3;
    Image backgroundImage;
    ImageIcon icon;
    public JImageButtonTest()
    super( "Test for JImageButton" );
    Toolkit tk = Toolkit.getDefaulttoolkit();
    // Replace "someImage" and "anotherImage" with your own
    // images...
    backgroundImage = tk.getImage( "someImage.gif" );
    Image iconImage = tk.getImage( "anotherImage.gif" );
    icon = new ImageIcon( iconImage );
    jib1 = new JImageButton( "Button 1" );
    jib2 = new JImageButton( "Button 2" );
    jib3 = new JImageButton( "Button 3", icon );
    jib2.setBackgroundImage( backgroundImage );
    jib3.setBackgroundImage( backgroundImage );
    jb1 = new JButton( "JButton 1" );
    jb2 = new JButton( "JButton 2", icon );
    JPanel p1 = new JPanel();
    p1.add( jib1 );
    p1.add( jib2 );
    p1.add( jib3 );
    JPanel p2 = new JPanel();
    p2.add( jb1 );
    p2.add( jb2 );
    getContentPane().add( p1, BorderLayout.SOUTH );
    getContentPane().add( p2, BorderLayout.NORTH );
    public static void main( String[] args )
    JImageButtonTest jibt = new JImageButtonTest();
    jibt.addWindowListener( new ExitHandler() );
    jibt.pack();
    jibt.setVisible( true );
    class ExitHandler extends WindowAdapter
    public void windowClosing( WindowEvent e )
    System.exit( 0 );

    Hi noamt3,
    Please look this my test case's below it's working fine here.
    import java.awt.*;
    import javax.swing.*;
    public class JImageButton extends JButton
    Image backgroundImage;
    public JImageButton()
    super();
    public JImageButton( Action a )
    super( a );
    public JImageButton( Icon icon )
    super( icon );
    public JImageButton( String text )
    super( text );
    public JImageButton( String text, Icon icon )
    super( text, icon );
    public void setBackgroundImage( Image image )
    MediaTracker mt = new MediaTracker( this );
    mt.addImage( image, 0 );
    try
    mt.waitForAll();
    backgroundImage = image;
    catch( InterruptedException x )
    System.err.println(
    "Specified background image could not be loaded." );
    public void paintComponent( Graphics g )
    super.paintComponent( g );
    Color saved = g.getColor();
    g.setColor( getBackground() );
    g.fillRect( 0, 0, getWidth(), getHeight() );
    g.setColor( saved );
    if( backgroundImage != null )
    int imageX = ( getWidth() - backgroundImage.getWidth( this ) ) / 2;
    int imageY = ( getHeight() - backgroundImage.getHeight( this ) ) / 2;
    g.drawImage( backgroundImage, imageX, imageY, this );
    if( !getText().equals( "" ) )
    g.drawString( super.getText(), getWidth() / 2, getHeight() / 2 );
    if( getIcon() != null )
    Icon icon = getIcon();
    icon.paintIcon( this, g, 10, 10 );
    public Dimension getPreferredSize()
    Dimension oldSize = super.getPreferredSize();
    Dimension newSize = new Dimension();
    Dimension returnSize = new Dimension();
    if( backgroundImage != null )
    newSize.width = backgroundImage.getWidth( this ) + 1;
    newSize.height = backgroundImage.getHeight( this ) + 1;
    if( oldSize.height > newSize.height )
    returnSize.height = oldSize.height;
    else
    returnSize.height = newSize.height;
    if( oldSize.width > newSize.width )
    returnSize.width = oldSize.width;
    else
    returnSize.width = newSize.width;
    return( returnSize );
    Here tester testcase:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class JImageButtonTest extends JFrame
    JButton jb1, jb2;
    JImageButton jib1, jib2, jib3;
    Image backgroundImage;
    ImageIcon icon;
    public JImageButtonTest()
    super( "Test for JImageButton" );
    Toolkit tk = Toolkit.getDefaultToolkit();
    // Replace "someImage" and "anotherImage" with your own
    // images...
    backgroundImage = tk.getImage( "someImage.gif" );
    Image iconImage = tk.getImage( "anotherImage.gif" );
    icon = new ImageIcon( iconImage );
    jib1 = new JImageButton( "Button 1" );
    jib2 = new JImageButton( "Button 2" );
    jib3 = new JImageButton( "Button 3", icon );
    jib2.setBackgroundImage( backgroundImage );
    jib3.setBackgroundImage( backgroundImage );
    jb1 = new JButton( "JButton 1" );
    jb2 = new JButton( "JButton 2", icon );
    JPanel p1 = new JPanel();
    p1.add( jib1 );
    p1.add( jib2 );
    p1.add( jib3 );
    JPanel p2 = new JPanel();
    p2.add( jb1 );
    p2.add( jb2 );
    getContentPane().add( p1, BorderLayout.SOUTH );
    getContentPane().add( p2, BorderLayout.NORTH );
    public static void main( String[] args )
    JImageButtonTest jibt = new JImageButtonTest();
    jibt.addWindowListener( new ExitHandler() );
    jibt.pack();
    jibt.setVisible( true );
    class ExitHandler extends WindowAdapter
    public void windowClosing( WindowEvent e )
    System.exit( 0 );
    I hope this will help you out.
    Regards,
    Tirumalarao
    Developer Technical Support,
    Sun Microsystems,
    http://www.sun.com/developers/support.

Maybe you are looking for

  • HT203176 My start-up disc is nearly full.  I have another disc, an ex-time machine disc, that is available.  How do I make it known to the system so it can be used?

    I am getting a message that my 250 gb hard drive is nearly full.  I have deleted many files without making much difference.  I am unable to update any software now.  I have a 500 GB drive that was used for Time Machine but is now available to use.  I

  • FIFO - Goods Issue to Purchase relation

    Hello Experts, My client maintains the Inventory in FIFO model. They wants to know the corresponding purchase (GR PO/Invoice) of the Item issued (delivery/transfer) from a wharehouse. From whare I can generate this info? If any one is having a query

  • How do I receive a mobile number?

    I have just received a new iphone 4 after accidentaly damaging my other one, but this iphone has not given me a mobile number. It has given me the sim card and its ID number but no mobile number. How can I find out what this is? Also, it says it is c

  • CS5 12.0.3 Update

    Just checked within the CS5 application (Help > Updates) and advised that 12.0.3 is available. When following the 'more info' link within the update dialogue it leads to the Adobe updates page where no mention (hence no further info) is made regardin

  • Restore from Backup without saving

    How do I stop iTunes from saving an additional backup when I am restoring to backup on a new iPhone. It takes up alot of space and I do not have enough, hence the process stops after some time.