将JLabel放置在JPanel上的特定x,y坐标上 [英] Placing a JLabel at a specific x,y coordinate on a JPanel

查看:583
本文介绍了将JLabel放置在JPanel上的特定x,y坐标上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在JPanel上的特定X和Y坐标处放置一系列JLabel(并设置其高度和宽度)。无论我做什么,每个标签都会立即卷到前一个标签的右侧,并且与所有其他标签的尺寸完全相同。

I'm trying to place a series of JLabels at specific X and Y coordinates on a JPanel (and set its height and width, too). No matter what I do, each label winds up immediately to the right of the previous label and has the exact same size as all of the others.

现在,我的Jpanel处于网格布局中。我尝试过Absolute Layout(非法参数异常结果),Free Design(没有标签出现),Flow Layout(一切都被挤到中心),以及其他一些。

Right now, my Jpanel is in a Grid Layout. I've tried Absolute Layout (illegal argument exception results), Free Design (no labels appear), Flow Layout (everything just gets squeezed to the center), and a few others.

不确定我需要做些什么来完成这项工作。有人可以帮忙吗?谢谢!

Not sure what I need to do to make this work. Can anyone help? Thanks!

JLabel lbl1 = new JLabel("label 1");
JLabel lbl2 = new JLabel("label 2");
JLabel lbl3 = new JLabel("label 3");
JLabel lbl4 = new JLabel("label 4");
JLabel lbl5 = new JLabel("label 5");

myPanel.add(lbl1);
myPanel.add(lbl2);
myPanel.add(lbl3);
myPanel.add(lbl4);
myPanel.add(lbl5);

lbl1.setLocation(27, 20);
lbl2.setLocation(123, 20);
lbl3.setLocation(273, 20);
lbl4.setLocation(363, 20);
lbl5.setLocation(453, 20);

lbl1.setSize(86, 14);
lbl2.setSize(140, 14);
lbl3.setSize(80, 14);
lbl4.setSize(80, 14);
lbl5.setSize(130, 14);


推荐答案

您必须将容器的布局设置为null:

You have to set your container's Layout to null:

myPanel.setLayout(null);

不过也是一个很好的建议,看看马蒂斯布局管理器,我猜它叫做GroupLayout现在。绝对定位的主要问题是当窗口改变其大小时会发生什么。

However is a good advise also to take a look at the Matisse Layout Manager, I guess it is called GroupLayout now. The main problem with absolute positioning is what happens when the window changes its size.

这篇关于将JLabel放置在JPanel上的特定x,y坐标上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆