简体   繁体   中英

JLabel positioning into JPanel

I have this code written to make a database connection and add a client:

//adding the left panel
JPanel left = new JPanel();
left.setPreferredSize(new Dimension(250, 500));
left.setLayout(new BoxLayout(left, BoxLayout.Y_AXIS));
add(left);

//adding the right panel
JPanel right = new JPanel();
right.setPreferredSize(new Dimension(250, 500));
right.setLayout(new BoxLayout(right, BoxLayout.Y_AXIS));
add(right);

//adding the jlabel title to the left panel
JLabel leftTitle = new JLabel("Add a client");
leftTitle.setAlignmentX(CENTER_ALIGNMENT);
left.add(leftTitle);

//adding the jlabel title to the right panel
JLabel rightTitle = new JLabel("Make a reservation");
rightTitle.setAlignmentX(CENTER_ALIGNMENT);
right.add(rightTitle);

//adding the jlabel "name"
JLabel nameL = new JLabel("Name:");
left.add(nameL);

and I want to move this JLabel here: 将“名字:”移到左边

I've tried doing nameL.setAlignmentX(LEFT_ALIGNMENT); but it's still not working

Your problem is that you've used a BoxLayout .

left.setLayout(new BoxLayout(left, BoxLayout.Y_AXIS));
                   ^^^^^^^^^

Your BoxLayout is set to align things centered along the y-axis, so no amount of setting alignment is going to change that. In order to fix your problem, you need a different layout manager like GroupLayout or CardLayout .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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