Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1476941
  • 博文数量: 254
  • 博客积分: 8696
  • 博客等级: 中将
  • 技术积分: 2961
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-03 16:46
文章分类

全部博文(254)

文章存档

2015年(4)

2014年(18)

2013年(16)

2012年(8)

2011年(25)

2010年(2)

2009年(74)

2008年(107)

分类: Java

2009-03-15 12:35:49

JFrame是顶级容器,而JPanel是普通容器。包含Swing组件的程序必须包含一个顶级容器,而Swing组件不可以直接加入到顶级容器中。

JFrame and JPanel

JFrame

Remember to import these three packages when working with Swing:

javax.swing.*  
java.awt.*      
java.awt.event.*

A JFrame object is the physical window that you'll be working with in the Swing API. Making a window appear on the screen is easy enough. Here's the code:

JFrame frame = new JFrame("Title Bar Text");        
frame.setSize(256,256);                            
frame.pack();                                      
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.show();                                      

I think that code is relatively simple, all it does is create a new JFrame with a size of 256x256, tell Java to exit when the JFrame is closed and shows the window.

JPanel

You probably want to get started putting components on your brand-new form. Maybe you've even figured out how to and you've discovered that is not what you bargained for. Well, what you don't know is that you need to add a JPanel to the JFrame's contentpane before adding components to the JPanel. Here's what the code looks like:

JFrame frame = new JFrame("Title Bar Text");
JPanel panel = new JPanel();
frame.setSize(256,256);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.show();

Now we are getting somewhere... You probably have already ran this code, so you've discovered that it doesn't look any different than the last example, and that's because JPanels are just containers for components, the different types of panes are added to the JFrame's contentpane and then components are added to the JPanel. Other than Layout objects which I tell you about later, that's all there is for your basic JPanel.

阅读(8845) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~