简体   繁体   English

使用GroupLayout在JPanel中将JLabel居中

[英]Center JLabel within JPanel with GroupLayout

I am kind of frustrated with the group layout. 我对团队布局感到沮丧。 How can I make it so that the label upLabel will be centered within the red upper panel? 如何使标签upLabel处于红色上部面板的中心?

This example is not working and I tried out a lot of things, so this was my last try before I kicked out the monitor out of the window ;-) 这个例子不起作用,我尝试了很多事情,所以这是我最后一次尝试将显示器踢出窗外之前的尝试;-)

I know that there are better ways to center to text within the JPanel , but I just wanted to play around and wanted to understand the basics. 我知道有更好的方法可以在JPanel以文本为中心,但是我只是想玩转并且想了解基本知识。 I read to examples from oracle.com, but they are much more complex and honestly easier to understand. 我从oracle.com上阅读了一些示例,但是它们更加复杂,并且说起来更容易理解。 But this simple task isn't working for me. 但是这个简单的任务对我不起作用。

Many greetings and thanks 许多问候和感谢

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();
    }
}
}

For horizontal alignment, change: 对于水平对齐,请更改:

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

To: 至:

JLabel upLabel = new JLabel("Dummy Text", SwingConstants.CENTER);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM