Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

java - 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. 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();
      }
    });
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...