java JLabel 不会与 JPanel.setLayout(null) 一起显示。为什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14309837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JLabel won't show with JPanel.setLayout(null). Why?
提问by Rodrigo
I want to show many different labels over a map, so I'm using null layout in my panel, and calling setLocation for each label. For some reason, though, the labels don't show. If I remove the pan.setLayout(null), then the label appears in the top-center of the panel. Why isn't null layout working with setPosition?
我想在地图上显示许多不同的标签,所以我在面板中使用空布局,并为每个标签调用 setLocation。但是,出于某种原因,标签没有显示。如果我删除 pan.setLayout(null),则标签会出现在面板的顶部中央。为什么 null 布局不能与 setPosition 一起使用?
package mapa;
import java.awt.*;
import javax.swing.*;
public class Mapa extends JFrame {
private static JPanel pan;
private static JLabel lab;
public Mapa() {
}
private static void createAndShowGUI() {
Mapa frame = new Mapa();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
lab = new JLabel("TEXTO");
lab.setBackground(Color.black);
lab.setForeground(Color.white);
lab.setOpaque(true);
lab.setVisible(true);
pan = new JPanel();
pan.setLayout(null);
pan.setPreferredSize(new Dimension(640,480));
pan.add(lab);
lab.setLocation(100, 100);
frame.getContentPane().add(pan, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
}
回答by Reimeus
This is the problem with absolute positioning (or null
layout). It requires you to set the sizes of all your components, otherwise they will stay are their default zero-size and won't appear. That's why it's always better to use a layout manager.
这是绝对定位(或null
布局)的问题。它要求您设置所有组件的大小,否则它们将保持默认的零大小并且不会出现。这就是为什么使用布局管理器总是更好的原因。
回答by rtheunissen
You have to set the size of the label explicitly; try using setBounds
instead of setLocation
. For example, lab.setBounds(100,100,200,30);
Also there's no need to call setVisible(true);
on the label.
您必须明确设置标签的大小;尝试使用setBounds
代替setLocation
. 例如,lab.setBounds(100,100,200,30);
也不需要调用setVisible(true);
标签。
Unless there's a very good reason to use a null layout and you know exactly what you're doing, using a layout manager is always where you should start.
除非有很好的理由使用空布局并且您确切地知道自己在做什么,否则使用布局管理器始终是您应该开始的地方。