要想在JFrame中绘图,必须构造一个组件对象并把它加到框架中,swing中JComponent类表示空组件。
public abstract class JComponent extends Container
该类是除顶层容器外所有 Swing 组件的基类。要使用继承自JComponent的组件,必须将该组件置于一个根为顶层 Swing 容器的包含层次结构(containment hierarchy)中。顶层 Swing 容器(如JFrame、JDialog和JApplet)是专门的组件,它们为其他 Swing 组件提供了绘制其自身的场所。有关包含层次结构的解释,请参阅《The Java Tutorial》中的 Swing Components and the Containment Hierarchy 一节。
With the exception of top-level containers, all Swing components whose names begin with "J" descend from theJComponentclass. For example,JPanel,JScrollPane,JButton, andJTableall inherit fromJComponent. However,JFrameandJDialogdon't because they implement top-level containers.处了顶层容器外,其他所有swing组件都是由JComponent类衍生而来.
定义一个JComponent的子类:
public class RectangleComponent extends JComponent{ public void paintComponent(Graphics g) { 此处是绘图指令 } }
将绘图指令放在paintComponent方法中,如果需要重新绘制组件,就调用该方法。
当第一次显示窗口,自动调用paintComponent方法,在调整窗口大小或窗口隐藏后再次显示时,也调用该方法。
该方法接受一个Graphics对象,保存图形状态:当前色彩,字体等用于绘图操作的数据。但graphics是基本类,当程序员强烈要求提供更加面向对象的绘图方法时,java的设计者就创建了扩展Graphics类的Graphics2D类。只要swing工具箱调用paintComponent方法,实际上就是传递一个Graphics2D类型的参数。绘制简单图形不需要此特性。因为想用更复杂的方法 绘制二维图形对象,所以要Graphics参数恢复为Graphics2D类型,这需要强制转换。
public void paintComponent(Graphics g)
Graphics2D g2=(Graphics2D)g; //恢复为Graphics2d
graphics2d 重要的方法draw()
draw(Shape s) Strokes the outline of a Shape using the settings of the current Graphics2D context.
public class RectangleComponent extends JComponent{ public void paintComponent(Graphics g) { Graphics2D g2=(Graphics2D) g; Rectangle box=new Rectangle(5,10,20,30); g2.draw(box); } }
package jcomponent; import java.awt.Rectangle; import javax.swing.JFrame; public class FrameViewer { public static void main(String[] args) { final int FRAME_WIDTH=300; final int FRAME_HEIGHT=400; JFrame jframe=new JFrame(); jframe.setSize(FRAME_WIDTH,FRAME_HEIGHT); jframe.setTitle("frame"); jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); RectangleComponent component=new RectangleComponent(); jframe.add(component); jframe.setVisible(true); } }
如果上面的程序要写成applet,要继承一个JApplet类
将绘图代码放在paint方法中,而不是paintComponent中。
写成applet程序,代码如下:
public class RectangleApplet extends JApplet{ public void paint(Graphics g) { Graphics2D g2=(Graphics2D) g; g2.setColor(Color.red); Rectangle box=new Rectangle(5,10,20,30); g2.draw(box); box.translate(15,25); g2.draw(box); } }
为运行applet,需要一个带有applet标签的html文件。
RectangleApplet.html
<applet code="RectangleApplet.class" width="300" height="400" >
</applet>