NetBeans中容器不显示用add方法添加的组件
在NetBeans中新建一个项目,继承一个JFrame类,在该类的构造函数中加入this.add(Component c);,其中Component是Java的组件,如按钮JButton、容器JPane等都是。添加组件后运行,会发现添加的组件并没有显示。而是用NetBeans的设计版面添加的组件则会显示。
问题原因很简单,默认的JFrame或其它容器的布局(Layout)为"自由布局",要让一个组件可以显示,必须具体制定组件的位置。该布局不像其它Layout一样,自动排版添加或者指定CENTER或EAST的位置。
Java官方有对各种Layout很好的说明和演示:
要用这些Layout,可以直接在设计界面里把布局修改成其它的:

不过这样会导致运行时版面只有个标题,这是因为版面大小是在"自由设计"里设定的。所以不建议在这里设置。在JFrame的构造函数的initComponents();函数后面,用this.setLayout()方法设置版面的Layout,如this.setLayout(new GridLayout(0,1));,这样就OK。记得import java.awt.*;
再推荐一个免费的第三方Layout:http://www.miglayout.com/
转载请注明:来自pugWoo's Life
本文地址:http://www.pugwoo.com/2009/12/19/java-layout.html
4 条评论
我要留言mulberry outlet 发表于 2011-11-22 at 16:41 回复 引用
christian louboutin replica high heels in our online uk store. Your shoes sales prices will save. Christian Louboutin Knockoffs shoes sale now, newest styles of christian louboutin high heels in hot sale now. Welcome to purchase!
mulberry outlet 发表于 2011-11-22 at 16:43 回复 引用
christian louboutin replica high heels in our online uk store. Your shoes sales prices will save. Christian Louboutin Knockoffs shoes sale now, newest styles of christian louboutin high heels in hot sale now. Welcome to purchase!
cheap ugg boots 木 发表于 2011-11-29 at 21:35 回复 引用