Java 使用GroupLayout在JPanel中居中JLabel

Java 使用GroupLayout在JPanel中居中JLabel,java,swing,awt,layout-manager,grouplayout,Java,Swing,Awt,Layout Manager,Grouplayout,我对团队布局有点失望。如何使标签upLabel位于红色上面板的中心 这个例子不起作用,我尝试了很多东西,所以这是我把显示器踢出窗口之前的最后一次尝试;-) 我知道有更好的方法可以在JPanel中以文本为中心,但我只是想玩玩,想了解基本知识。我读了oracle.com上的例子,但它们更复杂,更容易理解。但是这个简单的任务对我来说不起作用 很多问候和感谢 import java.awt.Color; import javax.swing.GroupLayout; import javax.swing

我对团队布局有点失望。如何使标签
upLabel
位于红色上面板的中心

这个例子不起作用,我尝试了很多东西,所以这是我把显示器踢出窗口之前的最后一次尝试;-)

我知道有更好的方法可以在
JPanel
中以文本为中心,但我只是想玩玩,想了解基本知识。我读了oracle.com上的例子,但它们更复杂,更容易理解。但是这个简单的任务对我来说不起作用

很多问候和感谢

import java.awt.Color;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.*;

public class Main1 extends JFrame{

public static void main(String[] args) {
    new Main1().begin();
}

public void begin() {
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

        setResizable(true);
        setSize(500, 500);
        setTitle("Hauptmenue");
        setLocationRelativeTo(null);
        setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        GroupLayout layout = new GroupLayout(this.getContentPane());
        this.getContentPane().setLayout(layout);

        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(true);

        JPanel up = new JPanel();
        up.setBackground(Color.RED);
        JPanel mid = new JPanel();
        JPanel bot = new JPanel();

        // von links
        layout.setHorizontalGroup(layout.createParallelGroup().
                addComponent(up,300, 400, Short.MAX_VALUE).
                addComponent(mid).
                addComponent(bot));
        // von oben
        layout.setVerticalGroup(layout.createSequentialGroup().addComponent(up).
                addComponent(mid).
                addComponent(bot));

        layout = new GroupLayout(up);
        up.setLayout(layout);

        JLabel upLabel = new JLabel("Dummy Text");

        layout.setHorizontalGroup(layout.createSequentialGroup().addComponent(upLabel, 300, 400, Short.MAX_VALUE));
        layout.setVerticalGroup(layout.createSequentialGroup().addComponent(upLabel));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

对于水平对齐,请更改:

JLabel upLabel = new JLabel("Dummy Text");
致:


GroupLayout实际上是为与JIgloo或Matisse+1等GUI构建器一起发布SSCE而设计的。:)哦,我的上帝:-)-现在我需要一个新的显示器:-)人们(包括我)经常忘记布局应该与组件对齐、组件边框、布局填充、布局空白提示等内容相结合,…经常忘记如何布局的想法应该建立在相当多的艺术基础上
JLabel upLabel = new JLabel("Dummy Text", SwingConstants.CENTER);