learning java AWT 手绘窗口

import java.awt.*;port java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;

public class HandDraw {
    private final int AREA_WIDTH = 500;
    private final int AREA_HEIGHT = 400;

    private int preX = -1;
    private int preY = -1;

    PopupMenu pop =  new  PopupMenu();
    MenuItem redItem = new MenuItem("red");
    MenuItem greenItem =  new MenuItem("green");
    MenuItem blueItem = new MenuItem("blue");

    BufferedImage image = new BufferedImage(AREA_WIDTH,AREA_HEIGHT, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();

    private Frame f = new Frame("Test");

    private DrawCanvas drawArea = new DrawCanvas();

    private  Color foreColor = new Color(255,0,0);
    public  void init(){
        ActionListener menuListener = e -> {
            if (e.getActionCommand().equals("green")){
                foreColor = new Color(0,255,0);
            }

            if (e.getActionCommand().equals("red")){
                foreColor = new Color(255,0,0);
            }
            if (e.getActionCommand().equals("blue")){
                foreColor = new Color(0,0,255);
            }
        };

        redItem.addActionListener(menuListener);
        greenItem.addActionListener(menuListener);
        blueItem.addActionListener(menuListener);

        pop.add(redItem);
        pop.add(blueItem);
        pop.add(greenItem);

        drawArea.add(pop);

        g.fillRect(0,0,AREA_WIDTH,AREA_HEIGHT);

        drawArea.setPreferredSize(new Dimension(AREA_WIDTH,AREA_HEIGHT));

        drawArea.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                if(preX > 0  && preY > 0){
                    g.setColor(foreColor);
                    g.drawLine(preX,preY, e.getX(),e.getY());
                }
                preY = e.getY();
                preX = e.getX();
                drawArea.repaint();
            }
        });

        drawArea.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()){
                    pop.show(drawArea, e.getX(),e.getY());
                }
                preX = -1;
                preY = -1;
            }
        });

        f.add(drawArea);
        f.pack();
        f.setVisible(true);

    };

    public static void main(String[] args) {
        new HandDraw().init();

    }

    class  DrawCanvas extends Canvas{
        public void paint(Graphics g){
            g.drawImage(image,0,0,null);
        }
    }
}

output:

posted @ 2019-08-01 16:37  嵌入式实操  阅读(209)  评论(0编辑  收藏  举报