Search code examples
javaswingjframetitlebar

center align the title in JFrame


I want to know how to center the JFrame title.I referred following link How to center align the title in a JFrame?

but I need to center title without putting spacing.


Solution

  • Consider leaving the title left-justified...but...this will get you near the center. For resizable frames, you need to rewrite the title on resize.

    JFrame t = new JFrame();
    t.setSize(600,300);
    t.setFont(new Font("System", Font.PLAIN, 14));
    Font f = t.getFont();
    FontMetrics fm = t.getFontMetrics(f);
    int x = fm.stringWidth("Hello Center");
    int y = fm.stringWidth(" ");
    int z = t.getWidth()/2 - (x/2);
    int w = z/y;
    String pad ="";
    //for (int i=0; i!=w; i++) pad +=" "; 
    pad = String.format("%"+w+"s", pad);
    t.setTitle(pad+"Hello Center");
    

    https://stackoverflow.com/a/9662974/3675925