[英]How to set left alignement JLabel in JPanel
I have a JPanel that I insert into my JFrame. 我有一个插入到JFrame中的JPanel。 Now, I want to display a JLabel on the left at my JPanel.
现在,我想在我的JPanel的左侧显示一个JLabel。 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. 使用此代码,我无法在JPanel的左侧显示JLabel,但在中央看到它。
How can I fixed it? 我该如何解决?
-You might wish to set the JLabel's horizontalAlignment property. -您可能希望设置JLabel的horizontalAlignment属性。 One way is via its constructor.
一种方法是通过其构造函数。 Try:
尝试:
JLabel label = new JLabel(lText, SwingConstants.LEFT);
This can also be done via the expected setter method: 也可以通过预期的setter方法完成此操作:
label.setHorizontalAlignment(SwingConstants.LEFT);
-You can also try using LEFT alignment for your JLabel JPanel container -您也可以尝试对JLabel JPanel容器使用LEFT对齐方式
myJPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
-Final way : -最终方式:
You could wrap the label in JPanel
with FlowLayout.LEADING
您可以使用
FlowLayout.LEADING
将标签包装在JPanel
JPanel wrapper = new JPanel(new FlowLayout(FlowLayout.LEADING,0, 0));
wrapper.add(Jlabel);
panel.add(wrapper);
Also remember to follow Java naming convention. 还请记住遵循Java命名约定。 variables begin with lower case letters using camel casing:
Jlabel
→ jLabel
变量使用驼峰大小写以小写字母开头:
Jlabel
→ jLabel
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.