生活随笔
收集整理的這篇文章主要介紹了
Java_画图软件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
簡介:本文講解如何用java寫一個簡單的畫圖軟件。
運行效果:
代碼:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;public class Main {private Frame frame
= new Frame("簡答手繪程序");private final int AREA_WIDTH = 500;private final int AREA_HEIGHT = 400;private PopupMenu colorMenu
= new PopupMenu(); private MenuItem redItem
= new MenuItem("紅色");private MenuItem greenItem
= new MenuItem("綠色");private MenuItem blueItem
= new MenuItem("藍色");private Color forceColor
= Color.BLACK;BufferedImage image
= new BufferedImage(AREA_WIDTH, AREA_HEIGHT, BufferedImage.TYPE_INT_BGR); Graphics g
= image
.getGraphics();private class MyCanves extends Canvas{@Overridepublic void paint(Graphics g
) {g
.drawImage(image
, 0, 0, null); }}MyCanves drawArea
= new MyCanves(); private int preX
= -1;private int preY
= -1;public void init(){ActionListener listener
= new ActionListener(){@Overridepublic void actionPerformed(ActionEvent e
) {String actionCommand
= e
.getActionCommand();switch (actionCommand
){case "紅色":forceColor
= Color.RED;break;case "綠色":forceColor
= Color.GREEN;break;case "藍色":forceColor
= Color.BLUE;break;}}};redItem
.addActionListener(listener
);greenItem
.addActionListener(listener
);blueItem
.addActionListener(listener
);colorMenu
.add(redItem
);colorMenu
.add(greenItem
);colorMenu
.add(blueItem
);drawArea
.add(colorMenu
);drawArea
.addMouseListener(new MouseAdapter() {@Overridepublic void mouseReleased(MouseEvent e
) {boolean popupTrigger
= e
.isPopupTrigger();if (popupTrigger
){ colorMenu
.show(drawArea
, e
.getX(), e
.getY());}preX
= -1;preY
= -1;}});g
.setColor(Color.white
);g
.fillRect(0, 0, AREA_WIDTH, AREA_HEIGHT);drawArea
.addMouseMotionListener(new MouseAdapter() {@Overridepublic void mouseDragged(MouseEvent e
) {if (preX
> 0 && preY
> 0){g
.setColor(forceColor
);g
.drawLine(preX
, preY
, e
.getX(), e
.getY());}preX
= e
.getX();preY
= e
.getY();drawArea
.repaint();}});drawArea
.setPreferredSize(new Dimension(AREA_WIDTH, AREA_HEIGHT));frame
.add(drawArea
);frame
.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e
) {System.exit(0);}});frame
.pack();frame
.setVisible(true);}public static void main(String[] args
){new Main().init();}
}
總結
以上是生活随笔為你收集整理的Java_画图软件的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。