如何在Java中通过带参数调用Canvas构造函数来创建Canvas对象?

问题描述 投票:0回答:2

你能帮我知道怎么做吗

  1. 使用ColorImage类的默认构造函数创建一个ColorImage对象?

  2. 通过带参数调用 Canvas 构造函数来创建 Canvas 对象。构造函数的第一个和第二个参数是 ColorImage 的宽度和高度。 ColorImage 的宽度和高度可以通过使用 ColorImage 类中的 getWidth() 和 getHeight() 方法获得。

java
2个回答
0
投票
    ColorImage image = new ColorImage();
    Canvas canvas = new Canvas(image.getWidth(), image.getHeight());
    canvas.add(image, 0, 0);

-1
投票
public class MyPaint {
public static void main(String[] args) {
    new PaintFrame("JavaPainter",100,300);
}

}

类 MyCanvas 扩展 JPanel 实现 MouseListener、MouseMotionListener {

private Vector<Point> curve;
private Vector<Vector<Point>> curves;

private Point ptFrom = new Point();
private Point ptTo = new Point();

MyCanvas() {
    curve = new Vector<Point>();
    curves = new Vector<Vector<Point>>();
    this.setPreferredSize(new Dimension(1, 1));
    this.addMouseListener(this);
    this.addMouseMotionListener(this);
}

public void paintComponent(Graphics g) {
    g.setColor(Color.RED);
    for (Vector<Point> points : curves) {
        Point pt0 = points.get(0);
        for (int i = 1; i < points.size(); ++i) {
            Point pt = points.get(i);
            g.drawLine(pt0.x, pt0.y, pt.x, pt.y);
            pt0 = pt;
        }
    }
}

@Override
public void mousePressed(MouseEvent e) {
    ptFrom.x = e.getX();
    ptFrom.y = e.getY();
    curve.add((Point) ptFrom.clone());
}

@Override
public void mouseReleased(MouseEvent e) {
    ptTo.x = e.getX();
    ptTo.y = e.getY();
    curve.add((Point) ptTo.clone());
    curves.add(new Vector<Point>(curve));
    curve.clear();
}

@Override
public void mouseDragged(MouseEvent e) {
    ptTo.x = e.getX();
    ptTo.y = e.getY();
    curve.add((Point) ptTo.clone());
    Graphics g = getGraphics();
    g.setColor(Color.RED);
    g.drawLine(ptFrom.x, ptFrom.y, ptTo.x, ptTo.y);
    ptFrom.x = ptTo.x;
    ptFrom.y = ptTo.y;
}

@Override
public void mouseEntered(MouseEvent e) {
    // do nothing
}

@Override
public void mouseExited(MouseEvent e) {
    // do nothing
}

@Override
public void mouseClicked(MouseEvent e) {
    // do nothing
}

@Override
public void mouseMoved(MouseEvent e) {
    // do nothing
}

}

PaintFrame 类扩展 JFrame {

private MyCanvas canvas = new MyCanvas();

PaintFrame(String title) {
    super(title);
    Container cp = getContentPane();
    cp.add(canvas);
    setSize(300, 200);
    setVisible(true);
}
PaintFrame(String title,Integer length,Integer width) {
    super(title);
    Container cp = getContentPane();
    cp.add(canvas);
    setSize(width, length);
    setVisible(true);
}

}

来自其他地方http://blog.csdn.net/fduan/article/details/8062556

© www.soinside.com 2019 - 2024. All rights reserved.