JPanel

JPanel

JPanel就是一个容器,对一个容器一般只有四个操作:设定layout(排列方式),add component,remove component,get component。

add(Componet,[int],[Object],[String]),其中int是component在panel中的index,默认index从0开始。Object和String表示一些有关layout的constraint信息,比如位置等。

panels do not add colors to anything except their own background; however, you can easily add borders to them and otherwise customize their painting.

Setting the Layout Manager

a panel uses a layout manager to position and size its components. By default, a panel's layout manager is an instance of FlowLayout, which places the panel's contents in a row. You can easily make a panel use any other layout manager by invoking the setLayout method or by specifying a layout manager when creating the panel. The latter approach is preferable for performance reasons, since it avoids the unnecessary creation of a FlowLayout object.

JPanel p = new JPanel(new BorderLayout()); //PREFERRED!

This approach does not work with BoxLayout, since the BoxLayout constructor requires a pre-existing container. Here is an example that uses BoxLayout.

JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS));

Adding Components

When the layout manager is FlowLayout, BoxLayout, GridLayout, or SpringLayout, you will typically use the one-argument add method, like this:

aFlowPanel.add(aComponent);
aFlowPanel.add(anotherComponent);

When the layout manager is BorderLayout, you need to provide an argument specifying the added component's position within the panel. For example:

aBorderPanel.add(aComponent, BorderLayout.CENTER);
aBorderPanel.add(anotherComponent, BorderLayout.PAGE_END);

With GridBagLayout you can use either add method, but you must somehow specify grid bag constraints for each component.

Reference: java api7

posted on 2014-03-12 19:33 HF_Cherish 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/hf-cherish/p/3597072.html

你可能感兴趣的:(JPanel)