Java AWT |画布类

Canvas类是JavaAWT的一部分。画布是一个空白的矩形区域,用户可以在其中绘制或捕获来自用户的输入。Canvas类继承组件类。 Canvas类的构造函数是:

null
  1. 画布() :创建一个新的空白画布。
  2. 画布(图形配置c) :使用指定的图形配置创建新画布。

Canvas类中常用的方法

方法 解释
addNotify() 创建画布的对等对象。
createBufferStrategy(int n) 为此组件创建多缓冲的新策略。
createBufferStrategy(int n,BufferC) 在这个组件上创建一个具有所需缓冲功能的多缓冲新策略
getBufferStrategy() 返回此组件使用的缓冲策略。
绘画(图形g) 绘制此组件。
更新(图形g) 更新这个画布。

下面的程序演示了Canvas类的使用:

  • 项目1: 创建画布并绘制画布。

JAVA

// Java Program to create a to create
// a canvas and paint the canvas
import java.awt.*;
import javax.swing.*;
class canvas extends JFrame {
// constructor
canvas()
{
super ( "canvas" );
// create a empty canvas
Canvas c = new Canvas() {
// paint the canvas
public void paint(Graphics g)
{
// set color to red
g.setColor(Color.red);
// set Font
g.setFont( new Font( "Bold" , 1 , 20 ));
// draw a string
g.drawString( "This is a canvas" , 100 , 100 );
}
};
// set background
c.setBackground(Color.black);
add(c);
setSize( 400 , 300 );
show();
}
// Main Method
public static void main(String args[])
{
canvas c = new canvas();
}
}


  • 输出:

图片[1]-Java AWT |画布类-yiteyi-C++库

  • 项目2: 创建画布并将鼠标侦听器添加到画布(在画布上单击或拖动鼠标的点将出现半径为5的圆圈)。

JAVA

// Java Program to create a
// canvas and mouse listener to the
// canvas ( a circle of radius 5 will appear
// at the points where mouse are clicked or
//  dragged on the canvas)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class canvas extends JFrame implements MouseListener, MouseMotionListener {
// create a canvas
Canvas c;
// constructor
canvas()
{
super ( "canvas" );
// create a empty canvas
c = new Canvas() {
public void paint(Graphics g)
{
}
};
// set background
c.setBackground(Color.black);
// add mouse listener
c.addMouseListener( this );
c.addMouseMotionListener( this );
add(c);
setSize( 400 , 300 );
show();
}
// mouse listener  and mouse motion listener methods
public void mouseClicked(MouseEvent e)
{
Graphics g = c.getGraphics();
g.setColor(Color.red);
// get X and y position
int x, y;
x = e.getX();
y = e.getY();
// draw a Oval at the point
// where mouse is moved
g.fillOval(x, y, 5 , 5 );
}
public void mouseMoved(MouseEvent e)
{
}
public void mouseDragged(MouseEvent e)
{
Graphics g = c.getGraphics();
g.setColor(Color.red);
// get X and y position
int x, y;
x = e.getX();
y = e.getY();
// draw a Oval at the point where mouse is moved
g.fillOval(x, y, 5 , 5 );
}
public void mouseExited(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
}
// main class
public static void main(String args[])
{
canvas c = new canvas();
}
}


  • 输出:

图片[2]-Java AWT |画布类-yiteyi-C++库

参考: https://docs.oracle.com/javase/7/docs/api/java/awt/Canvas.html

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享