Java/Swing - 工具提示矩形

4
我目前正在开发一个Java/Swing项目,而且我在自定义过程中遇到了问题。
我已经扩展了JToolTip并重写了paint()方法来绘制自己的工具提示,但我无法去掉工具提示周围的背景。
这是paint()的覆盖内容:
/* (non-Javadoc)
 * @see javax.swing.JComponent#paint(java.awt.Graphics)
 */
@Override
public void paint(Graphics g) {     
    String text = getComponent().getToolTipText();

    if (text != null && text.trim().length() > 0) {
        // set the parent to not be opaque
        Component parent = this.getParent();
        if (parent != null) {
            if (parent instanceof JComponent) {
                JComponent jparent = (JComponent) parent;
                if (jparent.isOpaque()) {
                    jparent.setOpaque(false);
                }
            }
        }

        // create a round rectangle
        Shape round = new RoundRectangle2D.Float(4, 4, this.getWidth() - 1 - 8, this.getHeight() - 1 - 8, 8, 8);

        // draw the background
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(getBackground());
        g2.fill(round);

        // draw the left triangle
        Point p1 = new Point(4, 10);
        Point p2 = new Point(4, 20);
        Point p3 = new Point(0, 15);
        int[] xs = {p1.x, p2.x, p3.x};
        int[] ys = {p1.y, p2.y, p3.y};
        Polygon triangle = new Polygon(xs, ys, xs.length);
        g2.fillPolygon(triangle);

        // draw the text
        int cHeight = getComponent().getHeight();
        FontMetrics fm = g2.getFontMetrics();
        g2.setColor(getForeground());
        if (cHeight > getHeight())
            g2.drawString(text, 10, (getHeight() + fm.getAscent()) / 2);
        else
            g2.drawString(text, 10, (cHeight + fm.getAscent()) / 2);

        g2.dispose();
    }
}

这是我想要移除的(白色)背景:
enter image description here

我在OSX下运行java 1.7.0_05。


1
这不是由 super.paint 绘制的吗? - dacwe
为了更快地获得更好的帮助,请发布一个SSCCE - Andrew Thompson
永远不要在 paint/Component 中改变组件状态。 - kleopatra
@dacwe 我在测试渲染时留下了 super.paint,但删除它没有任何效果,不幸的是。 - user1478292
2个回答

0
可能是因为您在调用super.paint之后将父级设置为不透明。此外,您是否在JToolTip上调用了setOpaque? 最后,您可以在addNotify中完成所有操作,而不是在每次绘制时执行代码:
public void addNotify() {
    super.addNotify();
    setOpaque(false);
    Component parent = this.getParent();
    if (parent != null) {
        if (parent instanceof JComponent) {
            JComponent jparent = (JComponent) parent;
            jparent.setOpaque(false);
        }
    }
}

谢谢@marco,但那并没有解决问题。无论如何,我现在正在使用addnotify()来设置父对象的不透明值,谢谢! - user1478292

0

问题在于所有组件默认都是矩形的形状 - 如果你想为工具提示构建自己的形状,你需要设置它:

Shape circle = new Ellipse2D.Float(-1.0f,-1.0f, 36.0f, 36.0f);
tooltip.setShape(circle);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接