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