核心Swing组件(七)

4.7 JPanel类

最后一个基本的Swing组件是JPanel组件。JPanel组件可以作为一个通常目的的窗口对象,替换了AWT的Panel窗口,而当我们需要一个可绘制的Swing组件区域时,JPanel替换了Canvas组件。

4.7.1 创建JPanel

JPanel有四个构造函数:

public JPanel()

JPanel panel = new JPanel();

 

public JPanel(boolean isDoubleBuffered)

JPanel panel = new JPanel(false);

 

public JPanel(LayoutManager manager)

JPanel panel = new JPanel(new GridLayout(2,2));

 

public JPanel(LayoutManager manager, boolean isDoubleBuffered)

JPanel panel = new JPanel(new GridLayout(2,2), false);

 

使用这些构造函数,我们可以修改FlowLayout中的默认布局管理器,或是通过执行true或false修改默认的双缓冲。

4.7.2 使用JPanel

我们可以将JPanel用我们通常目的的容器,或者是用作新组件的基类。对于通常目的容器,其过程很简单:创建面析,如果需要设置其布局管理器,并且使用add()方法添加组件。

JPanel panel = new JPanel();

JButton okButton = new JButton("OK");

panel.add(okButton);

JButton cancelButton = new JButton("Cancel");

panel.add(cancelButton);

 

当我们需要创建一个新的组件时,派生JPanel并且重写public void paintComponent(Graphics g)方法。尽管我们可以直接派生JComponent,但派生JPanel修改更为合理。列表4-8演示了一个组件绘制适应组件尺寸的椭圆的简单组件,同时包含一个测试驱动。

package swingstudy.ch04;

 

import java.awt.Color;

import java.awt.EventQueue;

import java.awt.Graphics;

import java.awt.GridLayout;

 

import javax.swing.JFrame;

import javax.swing.JPanel;

 

public class OvalPanel extends JPanel {

 

	Color color;

 

	public OvalPanel() {

		this(Color.black);

	}

 

	public OvalPanel(Color color) {

		this.color = color;

	}

 

	public void paintComponent(Graphics g) {

		int width = getWidth();

		int height = getHeight();

		g.setColor(color);

		g.drawOval(0, 0, width, height);

	}

	/**

	 * @param args

	 */

	public static void main(String[] args) {

		// TODO Auto-generated method stub

 

		Runnable runner = new Runnable() {

			public void run() {

				JFrame frame = new JFrame("Oval Sample");

				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 

				frame.setLayout(new GridLayout(2,2));

 

				Color colors[] = {Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW };

 

				for (int i=0;i<4;i++) {

					OvalPanel panel = new OvalPanel(colors[i]);

					frame.add(panel);

				}

 

				frame.setSize(300, 200);

				frame.setVisible(true);

			}

		};

 

		EventQueue.invokeLater(runner);

	}

 

}

 

图4-15显示了测试驱动的运行结果。

Swing_4_15

4.7.3 自定义JPanel观感

表4-16显示了JPanelUIResource相关的属性集合。对于JPanel组件,有五个不同的属性。这些设置也许会影响到面板内的组件。

JPanel UIResource元素

属性字符串

对象类型

Panel.background

Color

Panel.border

Border

Panel.font

Font

Panel.foreground

Color

PanelUI

String

4.8 小结

在本章中,我们探讨了所有Swing组件的基类:JComponent类。由讨论我们了解了所有组件的共同元素,例如工具提示,以及特定的组件,例如JLabel。同时我们了解了如何使用Icon接口以及ImageIcon类为组件添加图标,而GrayFilter图像过滤器用于禁止图标。

我们同时了解了AbstractButton组件,他是所有Swing按钮对象的根对象。我们了解了其数据模型接口,ButtonModel,以及这个接口的默认实现,DefalutButtonModel。接着,我们了解了JButton类,他是最简单的AbstractButton实现。最后,我们了解了作为基本Swing容器对象的JPanel。

在第5章中,我们将会深入一些复杂的AbstractButton实现:转换按钮。

你可能感兴趣的:(swing)