如何在 JFrame 中居中对齐标题? [英] How to center align the title in a JFrame?

查看:22
本文介绍了如何在 JFrame 中居中对齐标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have a JFrame with a Title. I want center align the title, so that it appears in the middle of the JFrame's title.

Thanks.

解决方案

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");

这篇关于如何在 JFrame 中居中对齐标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆