How to centralize the title of a JFrame?

3

I have a jFrame component and want to centralize the title of it, would it be possible?

    
asked by anonymous 29.10.2016 / 23:15

1 answer

6

Natively it is not possible, but there is a workaround that can be solved alternatively, found in this SOEn response , which would justify aligning the text to the left:

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontMetrics;
import javax.swing.JFrame;

/**
 *
 * @author diego
 */
public class JFrameTitleCenter {

    public void createAndShowGUI() {
        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");

        t.setVisible(true);
        t.setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JFrameTitleCenter().createAndShowGUI();
            }
        });
    }
}

The result:

Theabovesolutionhasasmalllimitation,whichistonotworkproperlyonresizablewindows,forthis,youneedtodetectresizingandrewritethetitleafterthisevent,asexplainedbelow.

Update

Ihavedevelopedawaytomakethecenteringaccordingtothesizeofthescreen,thatis,usingthemethodbelow,itispossibletoreleaseresizing,sothatthetitlewillbeadjustedtothenewwindowsize:

privatevoidtitleAlign(JFrameframe){Fontfont=frame.getFont();StringcurrentTitle=frame.getTitle().trim();FontMetricsfm=frame.getFontMetrics(font);intframeWidth=frame.getWidth();inttitleWidth=fm.stringWidth(currentTitle);intspaceWidth=fm.stringWidth(" ");
    int centerPos = (frameWidth / 2) - (titleWidth / 2);
    int spaceCount = centerPos / spaceWidth;
    String pad = "";
    // for (int i=0; i!=w; i++) pad +=" ";
    pad = String.format("%" + (spaceCount - 14) + "s", pad);
    frame.setTitle(pad + currentTitle);

}

What I did was to delegate to a method the centralization of the title, passing only the reference of the screen.

However, you have to make this method call every time the screen is resized, and just add ComponentListener , overwriting the method componentSized() " of the screen where you want to centralize the title:

seuJFrame.addComponentListener(new ComponentAdapter() {
    @Override
    public void componentResized(ComponentEvent e) {
        titleAlign(seuJFrame);
    }
});

After this, the screen will adjust the title automatically after each resizing.

    
29.10.2016 / 23:32