【问题标题】:Java SWT Button with text OVER image带有文本 OVER 图像的 Java SWT 按钮
【发布时间】:2012-10-01 19:28:00
【问题描述】:

SWT 不支持按钮中的“文本覆盖图像”。设置图像时,隐藏文本。实现这一目标的最佳方法是什么?

我能想到的最好的解决方法是将文本与图像“合并”...有谁知道一个好的 Java 库可以做到这一点吗?

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

【问题讨论】:

    标签: java image button text swt


    【解决方案1】:

    为什么这在 SWT 中没有实现?

    SWT 旨在寻找本地化。为此,SWT 将操作系统资源用于小部件。因此,SWT Buttons 看起来像操作系统按钮。图片上方或下方带有文本的按钮并不常见。

    我设法实现了某种可行的方法,但它很老套。或许你可以以此为起点:

    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();
    }
    

    如您所见,我使用GridData 来实现按钮的大小,并使用Listener 来为SWT.Paint 填充图像和文本。

    结果如下:

    【讨论】:

    • 感谢您的回复。我的目标是实现文本覆盖图像(不在上方或下方)。 SWT 实现没有理由不支持这个特性。如果 SO 可以本地显示图像,SWT 可以“合并”图像上的文本...
    • @marcolopes 您可以通过更改drawText 和drawImage 的坐标并颠倒它们的顺序来在图像上显示文本。
    猜你喜欢
    • 2011-01-08
    • 2012-12-07
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    • 2011-10-11
    • 2013-07-10
    相关资源
    最近更新 更多