【问题标题】:Drawing lines on canvas using Mouse without Swing in java在java中使用鼠标在画布上绘制线条而不使用Swing
【发布时间】:2019-08-21 03:45:06
【问题描述】:

我的问题和这个问题类似

Drawing lines with mouse on canvas : Java awt

我的问题是当窗口最小化和最大化时,绘制的线条每次都消失了

但我的工作完全不同,因为我只使用了awt组件,没有使用swing。

import java.awt.*;
import java.awt.event.*;
class Drawing extends WindowAdapter implements MouseMotionListener, MouseListener, ComponentListener {

    Frame f;
    Canvas c;
    int X=400,Y=400;
    int px=-1,py=-1;
    int x,y;

    public Drawing() {
        f=new Frame("Drawing - Canvas");
        f.addWindowListener(this);
        f.addComponentListener(this);
        f.setSize(X,Y);
        c=new Canvas();
        f.add(c);
        c.addMouseMotionListener(this);
        c.addMouseListener(this);
        f.setVisible(true);
    }

    public void componentResized(ComponentEvent e) {}
    public void componentHidden(ComponentEvent e) {}
    public void componentMoved(ComponentEvent e) {}
    public void componentShown(ComponentEvent e) {}

    public void mouseMoved(MouseEvent e) {}
    public void mouseClicked(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}

    public void mouseDragged(MouseEvent e) {
        int x,y;
        x=e.getX();
        y=e.getY();
        Graphics g=c.getGraphics();

        if(px!=-1) {    
            g.drawLine(px,py,x,y);
        }
        else {
            g.drawLine(x,y,x,y);
        }

        px=x;
        py=y;
    }

    public void mouseReleased(MouseEvent e) {
        this.X=400; this.Y=400;
        this.px=-1; this.py=-1;
    }

    public void windowClosing(WindowEvent e) {
        f.dispose();
    }

    public static void main(String[] args) {
      Drawing c=new Drawing();
    }   
}

有人可以帮我解决这些问题吗?

【问题讨论】:

    标签: java graphics awt


    【解决方案1】:

    getGraphics 绝不是执行自定义绘制的写入方式。

    首先阅读 Painting in AWT and SwingPerforming Custom Painting,以便更好地了解绘画的工作原理以及您应该如何使用它。

    简单的答案是,您需要维护已绘制的模型,以便在每次绘制时都可以重新绘制它。

    例如Resize the panel without revalidationDraw trail of circles with mouseDraggedWhy is my line not drawing?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-09
      • 2016-06-07
      • 2012-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      相关资源
      最近更新 更多