1

我对小组布局感到有点沮丧。我怎样才能使标签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();
    }
}
}
4

1 回答 1

2

对于水平对齐,更改:

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

至:

JLabel upLabel = new JLabel("Dummy Text", SwingConstants.CENTER);
于 2013-04-26T16:20:39.667 回答