问题描述
我有以下代码尝试在JFrame
上的自定义位置放置JLabel
.
I have the following code where I try to place a JLabel
in a custom location on a JFrame
.
public class GUI extends JFrame
{
/**
*
* @param args
*/
public static void main(String args[])
{
new GUI();
}
/**
*
*/
public GUI()
{
JLabel addLbl = new JLabel("Add: ");
add(addLbl);
addLbl.setLocation(200, 300);
this.setSize(400, 400);
// pack();
setVisible(true);
}
}
它似乎并没有移到我想要的地方.
It doesn't seem to be moving to where I want it.
推荐答案
问题是面板的LayoutManager
正在为您设置标签的位置.
The problem is that the LayoutManager
of the panel is setting the location of the label for you.
您需要做的是将布局设置为null:
What you need to do is set the layout to null:
public GUI() {
setLayout(null);
}
这将使框架不会尝试自行布置组件.
This will make it so the frame does not try to layout the components by itself.
然后调用 setBounds(Rectangle)
.像这样:
Then call setBounds(Rectangle)
on the label. Like so:
addLbl.setBounds(new Rectangle(new Point(200, 300), addLbl.getPreferredSize()));
这应该将组件放置在所需的位置.
This should place the component where you want it.
但是,如果您没有很好的理由自己布置组件,通常最好使用LayoutManagers
来帮助您.
However, if you don't have a really great reason to lay out the components by yourself, it's usually a better idea to use LayoutManagers
to work in your favor.
此处是关于入门的很棒的教程使用LayoutManager
s.
Here is a great tutorial on getting started with using LayoutManager
s.
如果您必须没有LayoutManager
,请此处是一个很好的入门教程.
If you must go without a LayoutManager
here is a good tutorial for going without one.
这篇关于为什么setLocation()不移动我的标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!