如何在JFrame中居中对齐标题?

时间:2012-03-12 06:02:05

标签: java swing jframe titlebar

我有一个 JFrame标题。我希望居中对齐标题,以便它显示在JFrame标题的中间

感谢。

5 个答案:

答案 0 :(得分:7)

考虑让标题保持左对齐......但是......这会让你靠近中心。对于可调整大小的帧,您需要在调整大小时重写标题。

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

答案 1 :(得分:4)

调整@ Java42的answer's source,在调整JFrame大小时我做了一个“解决方法”来调整标题:

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.JFrame;


public class JFrameTitleCenter {

    public void createAndShowGUI() {

        JFrame frame = new JFrame();
        frame.setPreferredSize(new Dimension(300, 200));
        frame.setTitle("Hello Center");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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

        });

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }

    private void titleAlign(JFrame frame) {

        Font font = frame.getFont();

        String currentTitle = frame.getTitle().trim();
        FontMetrics fm = frame.getFontMetrics(font);
        int frameWidth = frame.getWidth();
        int titleWidth = fm.stringWidth(currentTitle);
        int spaceWidth = fm.stringWidth(" ");
        int centerPos = (frameWidth / 2) - (titleWidth / 2);
        int spaceCount = centerPos / spaceWidth;
        String pad = "";
        pad = String.format("%" + (spaceCount - 14) + "s", pad);
        frame.setTitle(pad + currentTitle);

    }

    public static void main(String[] args) {

        EventQueue.invokeLater(() -> {
            new JFrameTitleCenter().createAndShowGUI();
        });
    }
}

工作:

enter image description here

答案 2 :(得分:2)

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.

简单无法在JFrames TitleBar中集中叙事,此容器来自Native OS

  • Windows操作系统中的实现getSystemLookAndFeel可以进行脏黑客攻击

  • 通过添加JFrame(模拟JPanel)与JButtons(带模拟标准按钮的图标的JButtons)创建未修饰的Toolbar

答案 3 :(得分:0)

我不知道你可以不使用复杂的方案。如果符合您的喜好,您可以将带有居中文本的标题边框应用于框架的内容窗格。

答案 4 :(得分:0)

在netbeans中,jFrame中的标题居中对齐非常容易,您需要执行的操作如下:

1。

enter image description here

2。

enter image description here

  1. 运行您的应用。

enter image description here