JLabel不会使用JPanel.setLayout(null)进行显示.为什么? [英] JLabel won't show with JPanel.setLayout(null). Why?

查看:53
本文介绍了JLabel不会使用JPanel.setLayout(null)进行显示.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在地图上显示许多不同的标签,因此我在面板中使用空布局,并为每个标签调用setLocation.但是由于某种原因,标签没有显示.如果删除pan.setLayout(null),则标签将出现在面板的顶部中心.为什么null布局不能与setPosition一起使用?

 程序包mapa;导入java.awt.*;导入javax.swing.*;公共类Mapa扩展了JFrame {专用静态JPanel锅;私人静态JLabel实验室;公共Mapa(){}私人静态void createAndShowGUI(){Mapa框架= 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 =新的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);}公共静态void main(String [] args){javax.swing.SwingUtilities.invokeLater(new Runnable(){@Override公共无效run(){createAndShowGUI();}});}} 

解决方案

这是绝对定位(或 null 布局)的问题.它要求您设置所有组件的大小,否则它们将保留为默认的零大小,并且不会显示.因此,最好使用布局管理器..>

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?

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). 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.

这篇关于JLabel不会使用JPanel.setLayout(null)进行显示.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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