我什至厌倦了 .setLocationRelativeTo(null) 但我想它只适用于 JFrame。我到处查了一下,但没有谷歌的信息。我也尝试过滚动浏览这些方法,但这里的方法太多了。请帮我。我还尝试输入 .set 然后滚动查看方法。
如果要将应用程序窗口框架居中,请使用
setLocationRelativeTo
。如果您希望将标签在 JPanel
内居中,您可以使用面板的布局管理器并使用 horizontalAlignment
将标签居中。
package org.example;
import java.awt.*;
import javax.swing.*;
public class CenterLabelApp implements Runnable {
private JPanel mainPanel;
protected CenterLabelApp() {
this.mainPanel = new JPanel();
setup();
}
private void setup() {
// Panel
this.mainPanel.setLayout(new BorderLayout());
this.mainPanel.setPreferredSize(new Dimension(400, 300));
// Label
JLabel label = new JLabel("Hello, World!");
label.setHorizontalAlignment(SwingConstants.CENTER); // Center the label horizontally
this.mainPanel.add(label, BorderLayout.CENTER); // Center the label vertically
}
@Override
public void run() {
JFrame frame = new JFrame("Center Label App");
frame.setContentPane(this.mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null); // Center the window
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new CenterLabelApp());
}
}
您还可以使用
JLabel
构造函数的第二个参数来设置对齐方式:
// Center the label horizontally
JLabel label = new JLabel("Hello, World!", SwingConstants.CENTER);