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?
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. I read to examples from oracle.com, but they are much more complex and honestly easier to understand. 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);