位置:首页 > Java技术 > AWT > AWT Canvas类

AWT Canvas类

介绍

Canvas控件代表一个矩形区域,应用程序可以画的东西,或者可以由用户创建的接收输入。

类的声明

以下是声明的java.awt.Canvas类:

public class Canvas
   extends Component
      implements Accessible

类的构造函数

S.N. 构造函数& 描述
1 Canvas() 
Constructs a new Canvas.
2 Canvas(GraphicsConfiguration config) 
Constructs a new Canvas given a GraphicsConfiguration object.

类方法

S.N. 方法& 描述
1 void addNotify() 
Creates the peer of the canvas.
2 void createBufferStrategy(int numBuffers) 
Creates a new strategy for multi-buffering on this component.
3 void createBufferStrategy(int numBuffers, BufferCapabilities caps) 
Creates a new strategy for multi-buffering on this component with the required buffer capabilities.
4 AccessibleContext getAccessibleContext() 
Gets the AccessibleContext associated with this Canvas.
5 BufferStrategy getBufferStrategy() 
Returns the BufferStrategy used by this component.
6 void paint(Graphics g) 
Paints this canvas.
7 void pdate(Graphics g) 
Updates this canvas.

继承的方法

这个类继承的方法从以下类:

  • java.awt.Component

  • java.lang.Object

Canvas 实例

选择使用任何编辑器创建以下java程序 D:/ > AWT > com > yiibai > gui >

AwtControlDemo.java
package com.yiibai.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showCanvasDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showCanvasDemo(){
      headerLabel.setText("Control in action: Canvas"); 

      controlPanel.add(new MyCanvas());
      mainFrame.setVisible(true);  
   } 

   class MyCanvas extends Canvas {

      public MyCanvas () {
         setBackground (Color.GRAY);
         setSize(300, 300);
      }

      public void paint (Graphics g) {
         Graphics2D g2;
         g2 = (Graphics2D) g;
         g2.drawString ("It is a custom canvas area", 70, 70);
      }
   }
}

编译程序,使用命令提示符。到 D:/ > AWT 然后键入以下命令。

D:AWT>javac comyiibaiguiAwtControlDemo.java

如果没有错误出现,这意味着编译成功。使用下面的命令来运行程序。

D:AWT>java com.yiibai.gui.AwtControlDemo

验证下面的输出

AWT Canvas