Incorrect behavior of JPanel#paintChildren(Graphics) when a JMenu is present?

后端 未结 1 1672
暖寄归人
暖寄归人 2020-12-06 14:05

What I want to do:
Create a JPanel\'s subclass to draw a simple overlay on top of contained components.

Why don\'t I use JLayeredPane

相关标签:
1条回答
  • 2020-12-06 14:52

    The first string is drawn outside of JPanel (under the JMenu), even though both coordinates are non-negative. The second string is NOT drawn at the bottom right corner. It is pushed up by the height of the JMenu.

    In both cases, note that drawString() expects the coordinates to represent the baseline of the String. The font;s ascent and descent are useful in this context. It may be a coincidence that mb.getHeight() and fm.getHeight() are of comparable magnitude.

    enter image description here

    @Override
    protected void paintChildren(Graphics g) {
        super.paintChildren(g);
    
        // draw some text
        FontMetrics fm = g.getFontMetrics();
        // will be drawn outside panel; under menu
        g.drawString("TEST TOP/LEFT", 0, fm.getAscent());
        final String s = "TEST BOTTOM/RIGHT";
        // will be drawn noticeably above the bottom
        g.drawString(s, getWidth() - fm.stringWidth(s),
            getHeight() - fm.getDescent());
    }
    
    0 讨论(0)
提交回复
热议问题