1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| public class CenterText extends JPanel {
public static void main(String[] args) {
SwingUtilities.invokeLater( ()->demo( new CenterText(SwingConstants.CENTER,SwingConstants.CENTER) ) );
}
private static void demo( final CenterText centerText ) {
final JFrame frame = new JFrame( "Démo" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize( 300, 300 );
frame.setLocationRelativeTo( null );
frame.getContentPane().add( centerText );
frame.setVisible(true);
}
private final static String STRING = "Démo";
private final int halign;
private final int valign;
public CenterText(int halign, int valign) {
this.halign=halign;
this.valign=valign;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
FontMetrics fontMetrics = g2d.getFontMetrics();
g2d.setColor(Color.YELLOW);
g2d.fillRoundRect(10, 10, 100, 50, 5, 5);
Rectangle2D bounds = new Rectangle2D.Double(10d, 10d, 100d, 50d);
g2d.setColor(Color.BLUE);
Rectangle2D textBounds = fontMetrics.getStringBounds(STRING, g2d);
double textWidth = textBounds.getWidth();
double x,y;
switch (halign) {
case SwingConstants.LEFT:
x = bounds.getX();
break;
case SwingConstants.RIGHT:
x = bounds.getX() + bounds.getWidth() - textWidth;
break;
case SwingConstants.CENTER:
default:
x = bounds.getX()
+ (bounds.getWidth() - textWidth) / 2;
break;
}
switch (valign) {
case SwingConstants.TOP:
y = bounds.getY() + fontMetrics.getAscent() - fontMetrics.getDescent();
break;
case SwingConstants.BOTTOM:
y = bounds.getY()
+ bounds.getHeight() - fontMetrics.getDescent() ;
break;
case SwingConstants.CENTER:
default:
y = bounds.getY()
+ bounds.getHeight()/ 2 - ( ( fontMetrics.getAscent() + fontMetrics.getDescent() ) / 2 ) + fontMetrics.getAscent() ;
break;
}
g2d.drawString(STRING, (int)x, (int)y);
}
} |
Partager