简体   繁体   English

在Java中使用不带鼠标的鼠标在画布上绘制线条

[英]Drawing lines on canvas using Mouse without Swing in java

My Quesition is similar to this question 我的问题类似于这个问题

Drawing lines with mouse on canvas : Java awt 在画布上用鼠标画线:Java AWT

My problem is that When the windows is minimized and maximized , the drawn lines are gone everytime 我的问题是,当窗口最小化和最大化时,绘制的线条每次都会消失

But my working is quite different because i used only awt components and without swing. 但是我的工作方式却大不相同,因为我只使用了awt组件,没有摆动。

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();
    }   
}

Can someone help me out on these problems ? 有人可以帮我解决这些问题吗?

getGraphics is NEVER the write way to perform custom paint. getGraphics从来不是执行自定义绘制的写方法。

Start by having a read through Painting in AWT and Swing and Performing Custom Painting for a better understanding how painting works and how you should work with it. 首先,请通读AWT中的“绘画”和“摇摆”和“ 执行自定义绘画” ,以更好地了解绘画的工作方式以及应该如何使用它。

The simple answer is, you need to maintain a model of what has been painted, so that on each paint pass you can re-draw it. 简单的答案是,您需要维护一个已绘制内容的模型,以便在每个绘制过程中都可以重新绘制它。

For example Resize the panel without revalidation , Draw trail of circles with mouseDragged , Why is my line not drawing? 例如, 调整面板大小而不进行重新验证使用mouseDragged绘制圆的轨迹为什么我的线没有绘制?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM