如何在codenameone中获得浮动帮助气泡或提示按钮?

时间:2018-04-24 10:21:01

标签: codenameone

我正在寻找一种在用户将鼠标悬停在按钮上时提供提示或帮助的方法。按钮组件没有文本组件的提示。

1 个答案:

答案 0 :(得分:1)

这些被称为工具提示,正如Francesco解释他们只在桌面应用程序中有意义...由于没有标准的方式使用它们但我们支持它们并在我们的桌面应用程序中使用它们。

E.g。此代码直接从我们的GUI构建器中提取,该构建器使用Codename One编写并具有工具提示:

public static void setTooltip(Component cmp, String t) {
    cmp.putClientProperty("tooltip", t);
}

public static void showTooltip(Component cmp, Form f) {
    final String t = (String)cmp.getClientProperty("tooltip");
    if(t == null) {
        f.setGlassPane(null);
    } else {
        int offset = Display.getInstance().convertToPixels(2) + 10;
        final Font fnt = cmp.getUIManager().getComponentStyle("Label").getFont();
        int width = fnt.stringWidth(t);
        int height = fnt.getHeight();

        int x = cmp.getAbsoluteX();
        if(x > f.getWidth() / 2) {
            x -= (width + offset);
        } else {
            x += cmp.getWidth() + offset;
        }
        int y = cmp.getAbsoluteY();
        if(y > f.getHeight() / 2) {
            y -= (height + offset);
        } else {
            y += cmp.getHeight() + offset;
        }

        final Rectangle rect = new Rectangle(x, y, width + 10, height + 10);
        final Rectangle shadow = new Rectangle(x + 5, y + 5, width + 10, height + 10);
        final Stroke s = new Stroke(3, Stroke.CAP_ROUND, Stroke.JOIN_ROUND, 1);
        f.setGlassPane(new Painter() {
            @Override
            public void paint(Graphics g, Rectangle r) {
                g.setColor(0);
                g.setAlpha(120);
                g.fillShape(shadow);
                g.setAlpha(255);
                g.setColor(0xeeeeee);
                g.fillShape(rect);
                g.setColor(0);
                g.drawShape(rect, s);
                g.setColor(0);
                g.setFont(fnt);
                g.drawString(t, rect.getX()  + 5, rect.getY() + 5);
            }
        });
    }
}

此代码应位于Form子类中:

@Override
public void pointerHover(int[] x, int[] y) {
    Component c = getComponentAt(x[0], y[0]);
    if(c != null) {
        GuiBuilderUtils.showTooltip(c, this);   
    }        
}