且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在JPanels中居中JLabel

更新时间:2023-12-05 22:27:58

调用 pack()是使用布局的关键步骤。此示例使用 JLabel.CENTER GridLayout 在调整帧大小时使标签居中。为简单起见,中心面板只是一个占位符。这个稍微复杂的示例使用了类似的方法以及 java.text.MessageFormat

Invoking pack() is a critical step in using layouts. This example uses JLabel.CENTER and GridLayout to center the labels equally as the frame is resized. For simplicity, the center panel is simply a placeholder. This somewhat more complex example uses a similar approach along with java.text.MessageFormat.

附录:但我将如何申请 pack() 到我的代码?

只需调用 pack(),如图所示引用的例子。我没有看到一种简单的方法来挽救你当前设定尺寸的方法。相反,在 getPreferredSize() > JPanel 代表您的主要内容。无论屏幕大小如何,您实施的 paintComponent对于示例,() 应适应当前大小。

Simply invoke pack() as shown in the examples cited. I don't see an easy way to salvage your current approach of setting sizes extrinsically. Instead, override getPreferredSize() in a JPanel for your main content. No matter the screen size, your implementation of paintComponent() should adapt to the current size, for example.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/** @see https://***.com/a/14422016/230513 */
public class Scores {

    private final JLabel[] nameLabel = new JLabel[]{
        new JLabel("Team 1", JLabel.CENTER),
        new JLabel("Team 2", JLabel.CENTER)};

    private void display() {
        JFrame f = new JFrame("Scores");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel teamPanel = new JPanel(new GridLayout(1, 0));
        teamPanel.add(nameLabel[0]);
        teamPanel.add(nameLabel[1]);
        f.add(teamPanel, BorderLayout.NORTH);
        f.add(new JPanel() {

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(320, 240);
            }
        }, BorderLayout.CENTER);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Scores().display();
            }
        });
    }
}