简体   繁体   English

JLabel不会与JPanel.setLayout(null)一起显示。 为什么?

[英]JLabel won't show with JPanel.setLayout(null). Why?

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. 我想在地图上显示许多不同的标签,所以我在面板中使用空布局,并为每个标签调用setLocation。 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. 如果删除pan.setLayout(null),则标签将出现在面板的顶部中央。 Why isn't null layout working with setPosition? 为什么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();
      }
    });
  }
}

This is the problem with absolute positioning (or null layout). 这是绝对定位(或null布局)的问题。 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 . 这就是为什么使用布局管理器总是更好的原因。

You have to set the size of the label explicitly; 您必须显式设置标签的大小; try using setBounds instead of setLocation . 尝试使用setBounds而不是setLocation For example, lab.setBounds(100,100,200,30); 例如, lab.setBounds(100,100,200,30); Also there's no need to call setVisible(true); 同样也不需要调用setVisible(true); on the label. 在标签上。

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. 除非有充分的理由使用空布局,并且您完全知道自己在做什么,否则始终应该使用布局管理器作为起点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM