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
The first string is drawn outside of
JPanel
(under theJMenu
), 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 theJMenu
.
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.
@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());
}