简体   繁体   中英

How to set left alignement JLabel in JPanel

I have a JPanel that I insert into my JFrame. Now, I want to display a JLabel on the left at my JPanel. So I have this code:

JPanel panelHeader = new JPanel();
panelHeader.setBackground(new Color(52,151,236));
panelHeader.setPreferredSize(new Dimension(300,25));

GridBagConstraints GBC = new GridBagConstraints();
Container CR = new Container();
GridBagLayout GBL = new GridBagLayout();
CR.setLayout(GBL);     
panelHeader.add(CR);

LabelFormat label = new LabelFormat("EasyManagement",new Font("Arial Narrow", Font.PLAIN, 16),Color.white);
GBC = new GridBagConstraints();
CR.add(label);
GBC.gridx=0;
GBC.gridy=0;
GBC.insets.left = 1;
GBC.insets.top=0;
GBC.fill = GridBagConstraints.BOTH;
GBC.anchor= GridBagConstraints.EAST;
GBL.setConstraints(label,GBC);

With this code, I'm not able to display the JLabel at the left on JPanel but I see it on the center.

How can I fixed it?

-You might wish to set the JLabel's horizontalAlignment property. One way is via its constructor. Try:

JLabel label = new JLabel(lText, SwingConstants.LEFT);

This can also be done via the expected setter method:

label.setHorizontalAlignment(SwingConstants.LEFT);

-You can also try using LEFT alignment for your JLabel JPanel container

myJPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); 

-Final way :

You could wrap the label in JPanel with FlowLayout.LEADING

JPanel wrapper = new JPanel(new FlowLayout(FlowLayout.LEADING,0, 0));
wrapper.add(Jlabel);
panel.add(wrapper);

在此处输入图片说明


Also remember to follow Java naming convention. variables begin with lower case letters using camel casing: JlabeljLabel

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