简体   繁体   English

Java SWT - 禁用按钮上的图像

[英]Java SWT - Images on disabled buttons

I use Buttons with Images in my SWT Gui and from time to time I have to disable them. 我在我的SWT Gui中使用Buttons with Images,并且我不得不禁用它们。

This lets SWT create an automatic disabled image from the colored image I placed previously on the button, and the disabled icon really does not really look pretty. 这让SWT从我之前放在按钮上的彩色图像中创建一个自动禁用的图像,并且禁用的图标实际上看起来并不漂亮。 I would like to place my own disabled image on the button, but I don't find a way to do this. 我想在按钮上放置我自己的禁用图像,但我找不到这样做的方法。

Is there one? 有吗?

You can't subclass Button so you need to do it at the time you enabled/disable the button. 您不能将Button子类化,因此您需要在启用/禁用按钮时执行此操作。 I couldn't find the SWT -> Windows Event mapping ID to invoke addListener on the button to make it more generic. 我找不到SWT - > Windows事件映射ID来调用按钮上的addListener以使其更通用。

public static void main(String[] args) throws Exception
{
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout(1, true));

    final Image image1 = new Image(null, new FileInputStream(
            "C:\\tmp\\enabled.png"));
    final Image image2 = new Image(null, new FileInputStream(
            "C:\\tmp\\disabled.png"));

    final Button button= new Button(shell, SWT.NONE);
    button.setText("Hello World SWT");
    button.setImage(image1);
    button.pack();

    final Button cb = new Button(shell, SWT.CHECK);
    cb.setText("Check me");
    cb.addSelectionListener(new SelectionAdapter()
    {
        @Override
        public void widgetSelected(SelectionEvent event)
        {
            button.setEnabled(!cb.getSelection());
            if (button.isEnabled())
                button.setImage(image1);
            else
                button.setImage(image2);
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

One other tip which may or may not save you a lot of trouble. 另一个提示可能会或可能不会给您带来很多麻烦。 Make sure the alpha levels on your image go all the way to zero for the transparent portions, especially near the edges, and the standard default disabled look may look a lot better. 确保图像上的alpha级别对于透明部分一直变为零,特别是在边缘附近,标准默认禁用外观可能看起来好多了。

I fixed my problem by modifying the Button class itself. 我通过修改Button类本身修复了我的问题。 It caches the disabled images now and reuses them when needed. 它现在缓存禁用的图像,并在需要时重用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM