Changing org.eclipse.swt.widgets background color in Windows

Solution 1:

On windows operating systems button.setBackGround doesn't work directly. A small snippet of code can help. Override the paint event of button as shown below:-

-----obj is button name in below snippet------------

obj.addPaintListener(new PaintListener() {
@Override
    public void paintControl(PaintEvent arg0) {
    // TODO Auto-generated method stub
    obj.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
    org.eclipse.swt.graphics.Pattern pattern;
    pattern = new org.eclipse.swt.graphics.Pattern(arg0.gc.getDevice(), 0,0,0,100, arg0.gc.getDevice().getSystemColor(SWT.COLOR_GRAY),230, arg0.gc.getDevice().getSystemColor(SWT.COLOR_BLACK),230);
    arg0.gc.setBackgroundPattern(pattern);
    arg0.gc.fillGradientRectangle(0, 0, obj.getBounds().width, obj.getBounds().height, true);
    }
});

Solution 2:

You can't. In the documentation of method Control.setBackground(), it is mentioned:

For example, on Windows the background of a Button cannot be changed.

Solution 3:

The background of a button in Windows is set from outside of SWT.

Right-click your desktop, click Properties.

Go to the "Appearance" tab.

Click "Advanced".

I believe "3D objects" determines the button background. This is determined by each user's theme.

alt text

One great thing about SWT is it uses the underlying system widgets and themes. A frustrating thing about SWT is it uses the underlying system widgets and themes.

Solution 4:

You can simulate a button using CLabel. Add a mouselistener to change the background on mouse down and mouse up, and in the mouse up event dispatch a selection listener event so that it behaves the same as a button. For example:

Color bg = ...
Color shadow = ...
CLabel simulatedButton = new CLabel(parent, SWT.PUSH);
simulatedButton.setBackground(bg); 
simulatedButton.addMouseListener(new MouseAdapter() {

  @Override
  public void mouseUp(MouseEvent e) {
    simulatedButton.setBackground(bg);
    notifyListeners(SWT.Selection, new Event());
  }

  @Override
  public void mouseDown(MouseEvent e) {
    simulatedButton.setBackground(shadow);
  }
});

This briefly changes the background of the button while you are pressing the mouse to give the effect of clicking a button. CLabel can also be extended, unlike other SWT widgets, so you can create a subclass if you need to do this often.

Solution 5:

No You cannot change the Background of a Button is SWT. You can find this information in Eclipse SWT documentation.

Eclipse SWT Documentation Button

public void setBackground(Color color)

Sets the receiver's background color to the color specified by the argument, or to the default system color for the control if the argument is null.

Note: This operation is a hint and may be overridden by the platform. For example, on Windows the background of a Button cannot be changed.