Java / Swing - 工具提示矩形

时间:2012-07-02 21:33:02

标签: java macos swing tooltip paint

我目前正在开发一个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。

2 个答案:

答案 0 :(得分: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);
        }
    }
}

答案 1 :(得分:0)

存在一个问题,所有组件默认都具有矩形形状-如果您要为工具提示构建自己的shape,则必须进行设置:

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