在 JPanel 上的特定 x,y 坐标处放置 JLabel [英] Placing a JLabel at a specific x,y coordinate on a JPanel
问题描述
我正在尝试在 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 处于网格布局中.我尝试过绝对布局(非法参数异常结果)、自由设计(不显示标签)、流布局(一切都被挤压到中心)和其他一些.
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);
推荐答案
您必须将容器的布局设置为空:
You have to set your container's Layout to null:
myPanel.setLayout(null);
然而,看看 Matisse Layout Manager 也是一个很好的建议,我猜它现在被称为 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.
这篇关于在 JPanel 上的特定 x,y 坐标处放置 JLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!