如何更改SWT按钮背景颜色或使其透明

时间:2014-02-09 14:07:30

标签: java button swt eclipse-rcp

我在Button(无文字)上有一张透明图片,该图片位于Composite上。由于Composite为白色(使用FormToolkit#createComposite(parent, SWT.NONE)创建),因此我希望Button背景颜色相同。我该怎么做?

Label可以解决这个问题,但是当我点击它时没有像Button那样的阴影。

1 个答案:

答案 0 :(得分:1)

Button的背景颜色由OS决定。实际上,Control.setBackground()的文档指出:

  

注意:此操作是一个提示,可能会被平台覆盖。例如,在Windows上,无法更改Button的背景。

尽管如此,绕过这一点的一种可能方法是覆盖paint事件,如下所示:Changing org.eclipse.swt.widgets background color in Windows。当我尝试这个时,结果有点不稳定。

最安全,最一致的方法是使用第二张图片中的标签,但要在各种鼠标事件上显示不同的图像,以模拟按钮的行为方式。

这些图像可以通过向图像本身添加任何形状的阴影来模拟阴影。该阴影也可以针对每张图片进行更改,以给人留下按钮被按下的印象。

例如,我正在考虑以下几点:

public class MyButton { 

    private final Label buttonLabel;

    public MyButton(final Composite parent, final Theme theme) {
        buttonLabel = new Label(parent, SWT.NONE);
        buttonLabel.setImage(theme.getUpImage());
        buttonLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseDown(final MouseEvent mouseEvent) {
                buttonLabel.setImage(theme.getButtonPressedImage());
            }
            @Override
            public void mouseUp(final MouseEvent mouseEvent) {
                buttonLabel.setImage(theme.getButtonUpImage());
            }
        });
        buttonLabel.addMouseTrackListener(new MouseTrackAdapter() {
            @Override
            public void mouseEnter(final MouseEvent mouseEvent) {
                buttonLabel.setImage(theme.getButtonHoverImage());
            }
            @Override
            public void mouseExit(final MouseEvent mouseEvent) {
                buttonLabel.setImage(theme.getButtonUpImage());
            }
        });
    }

}

Theme只是已经方便地加载了所有图像。

您还需要确保父Composite的背景模式设置为强制其背景颜色:

parent.setBackgroundMode(SWT.INHERIT_FORCE);

显然,这种方法的缺点是你必须自己处理鼠标点击逻辑(即在释放鼠标之前没有真正点击mouseDown,所以你必须处理每个监听器中按钮的状态法)。