栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

setLayout(null)时,JPanel上的组件未显示

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

setLayout(null)时,JPanel上的组件未显示

  • 几乎不使用空布局
  • 而是使用嵌套在JPanels中的布局的最佳组合来为您的GUI实现令人愉悦的布局。
  • 如果您确实使用null布局,那么您将完全负责设置添加到该容器的 所有 组件的大小和位置。
  • 当前的问题是,您永远不会给TestView指定大小或位置,而是将其添加到使用空布局的容器中。
  • 您不应将一个组件(上面的JComboBox)添加到多个容器中。
  • 在添加所有组件并对其进行调用
    setVisible(true)
    之前 请勿调用Jframe
    pack()

例如,

import java.awt.*;import javax.swing.*;public class TestController extends JPanel {   private static final int PREF_W = 1000;   private static final int PREF_H = 800;   TestView cgView;   public TestController() {      setLayout(null);      cgView = new TestView();      cgView.setSize(getPreferredSize());      add(cgView);   }   @Override   public Dimension getPreferredSize() {      return new Dimension(PREF_W, PREF_H);   }   public static void main(String[] args) {      SwingUtilities.invokeLater(new Runnable() {         public void run() { Jframe fr = new Jframe("testt"); // fr.setSize(1200, 1000); fr.setResizable(false); TestController cgc = new TestController(); fr.setBackground(Color.white); // fr.setVisible(true); fr.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); fr.add(cgc); fr.pack(); //!! added  fr.setVisible(true); // !! moved         }      });   }}

但是最好使用布局:

import java.awt.*;import javax.swing.*;public class TestController extends JPanel {   private static final int PREF_W = 1000;   private static final int PREF_H = 800;   TestView cgView;   public TestController() {      //!!  setLayout(null);      cgView = new TestView();      //!! cgView.setSize(getPreferredSize());      add(cgView);   }   @Override   public Dimension getPreferredSize() {      return new Dimension(PREF_W, PREF_H);   }   public static void main(String[] args) {      SwingUtilities.invokeLater(new Runnable() {         public void run() { Jframe fr = new Jframe("testt"); // fr.setSize(1200, 1000); fr.setResizable(false); TestController cgc = new TestController(); fr.setBackground(Color.white); // fr.setVisible(true); fr.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); fr.add(cgc); fr.pack(); //!! added  fr.setVisible(true); // !! moved         }      });   }}class TestView extends JPanel {   private static final long serialVersionUID = 1L;   public JComboBox<String> comboBox;   public TestView() {      comboBox = new JComboBox<String>(new String[] { "option1", "option2" });      // comboBox.setBounds(100, 500, 100, 20);      add(comboBox);   }}

编辑
OP在评论中询问:

‘几乎从不’?在哪种情况下,您会使用[null布局]?

我很少使用它,例如当我想通过动画或使用MouseListener来移动组件时,但是即使如此,许多人还是建议您创建自己的布局来处理它,例如Rob
Camick的Drag Layout。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/438962.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号