I have this code that creates a simply JPanel with text
User profile panel
username: a user
email: email@gmail.com
Button1 Button2
Each row - is a HorizontalBox
and all rows come into a VerticalBox
. I try to center the result VerticalBox
, but it doesn't work.
import javax.swing.*;
import java.awt.*;
public class TestProfile extends JPanel {
{
setup();
}
public void setup() {
Box vBoxUserData = Box.createVerticalBox();
Box hBoxUsername = Box.createHorizontalBox();
hBoxUsername.add(new JLabel("username: "));
hBoxUsername.add(new JLabel("a user"));
vBoxUserData.add(hBoxUsername);
Box hBoxEmail = Box.createHorizontalBox();
hBoxEmail.add(new JLabel("email: "));
hBoxEmail.add(new JLabel("email@gmail.com"));
vBoxUserData.add(hBoxEmail);
Box hBoxButtons = Box.createHorizontalBox();
hBoxButtons.add(new JButton("Button1"));
hBoxButtons.add(new JButton("Button2"));
Box vBoxContent = Box.createVerticalBox();
vBoxContent.add(new JLabel("User profile panel"));
vBoxContent.add(hBoxUsername);
vBoxContent.add(hBoxEmail);
vBoxContent.add(hBoxButtons);
vBoxContent.setAlignmentX(CENTER_ALIGNMENT);
vBoxContent.setAlignmentY(CENTER_ALIGNMENT);
hBoxUsername.setBackground(Color.RED);
add(vBoxContent);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new TestProfile());
frame.setVisible(true);
frame.setDefaultCloseOperation(
WindowConstants.EXIT_ON_CLOSE);
frame.setSize(600, 400);
}
}
It looks like this:
while I need it to look like this:
Also I'm confused why
hBoxUsername.setBackground(Color.RED);
didn't paint it in red?