带有文本OVER图像的Java SWT按钮

mar*_*pes 2 java swt text image button

SWT不支持Button中的"Text over Image".设置图像后,隐藏文本.有什么可能是实现这一目标的最佳方法?

我能想到的最好的解决方法是将文本与图像"合并"......有没有人知道一个好的Java库对此做了什么?

注意:我发现这个自定义实现只是在图像上绘制文本:https://github.com/jrobichaux/SquareButton/wiki.为什么在SWT中没有实现?(无论如何,我不能让这个班级工作......我真的不想要这种方法因为我想要NATIVE按钮看起来)

Baz*_*Baz 5

为什么在SWT中没有实现?

SWT旨在寻找本土人.为此,SWT使用OS资源作为小部件.因此,SWT Button看起来像操作系统按钮.图像上方或下方的按钮不常见.

我设法实现某种方式可行的东西,但它非常hacky.也许你可以用它作为起点:

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

    final Image image = display.getSystemImage(SWT.ICON_ERROR);
    final String text = "Button";

    final Button button = new Button(shell, SWT.PUSH);

    GridData data = new GridData();
    float fontHeight = shell.getFont().getFontData()[0].height;
    data.heightHint = image.getImageData().height + (int)fontHeight + 20;
    data.widthHint = 100;

    button.setLayoutData(data);

    button.addListener(SWT.Paint, new Listener() {

        @Override
        public void handleEvent(Event event) {
            GC gc = event.gc;

            int width = ((GridData)button.getLayoutData()).widthHint;
            int height = ((GridData)button.getLayoutData()).heightHint;
            Point textSize = gc.textExtent(text);

            gc.drawText(text, width / 2 - textSize.x / 2, image.getImageData().height - image.getImageData().height / 2 - textSize.y, true);
            gc.drawImage(image, width / 2 - image.getImageData().width / 2, height / 2 - image.getImageData().height / 2 + textSize.y / 2);
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    image.dispose();
    display.dispose();
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我以前GridData实现按键的大小和一个Listener用于SWT.Paint与图像和文本,以填充按钮.

结果如下:

在此输入图像描述