java畫板功能實現總結:
寫一個DrawLitenner類,繼承MouseListener,MouseMotionListener兩個接口:
public class DrawLitener implements MouseListener,MouseMotionListener { }
(一).畫直線:
利用鼠標按下監聽獲取座標(x1,y1),利用鼠標釋放監聽獲取座標(x2,y2).
if ("choose10".equals(command)) {
g.drawLine(x1, y1, x2, y2);
}
(二).畫圓:
利用鼠標按下監聽獲取座標(x1,y1),利用鼠標釋放監聽獲取座標(x2,y2).
else if ("choose14".equals(command)){
g.drawOval(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1-x2), Math.abs(y1-y2));
}
因爲g.drawOval(x,y,width,height)中四個參數x,y代表圓的外切矩形左上角座標,所以我們要用math函數分別取兩座標點的最小橫、縱座標。
(三)畫正方形:
利用鼠標拖動監聽獲取座標(x2,y2),利用鼠標釋放監聽獲取座標(x2,y2).
else if ("choose12".equals(command)){
g.drawRect(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1-x2), Math.abs(y1-y2));
}
(四)鉛筆:
利用鼠標按下監聽獲取坐邊(x1,y1),在鼠標再次拖動獲取新座標前將(x2,y2)賦給(x1,y1),在鼠標拖動獲取(x2,y2)後執行畫線操作將兩座標連接起來。
public void mouseDragged(MouseEvent e) {
if ("choose6".equals(command)) {
x2 = e.getX();
y2 = e.getY();
g.drawLine(x1, y1, x2 ,y2);
x1 = x2;
y1 = y2;
}
(五)橡皮:
橡皮的原理同鉛筆,只是將鉛筆的顏色更改成白色,筆的尺寸變粗,在執行完成後將筆的粗細、顏色變回原來的.
else if ("choose2".equals(command)){
Stroke stocke = new BasicStroke(10);
g.setStroke(stocke);
Color color = g.getColor();
g.setColor(Color.white);
x2 = e.getX();
y2 = e.getY();
g.drawLine(x1, y1, x2 ,y2);
x1 = x2;
y1 = y2;
stocke = new BasicStroke(1);
g.setStroke(stocke);
g.setColor(Color.black);
}
(六) 刷子:
刷子的原理同也同鉛筆,改變下鉛筆的粗細即可完成刷子的功能。
(七)噴桶:
用鼠標拖動監聽獲取座標,並利用隨機函數在獲取座標的點的附近隨機畫點
else if ("choose8".equals(command)){
x2 = e.getX();
y2 = e.getY();
for (int i = 0; i <20; i++) {
int r1 = rand.nextInt(30)-15;
int r2 = rand.nextInt(30)-15;
g.drawLine(x2+r1, y2+r2, x2+r1 ,y2+r2);
}
(八)多邊形的繪製:
獲取釋放點座標(x2,y2);
用一個布爾型做標記,若爲真執行鼠標按下和鼠標釋放點之間畫直線操作,並將標記值賦爲false,藉助全局變量x4,y4記錄x1,y1值,並將 x2,y2 賦值給 x3,y3。;
若標記值爲false,畫(x2,y2)到(x3,y3)的直線,並將 x2,y2 賦值給 x3,y3。
else if ("choose13".equals(command))
{
if(z == true){
g.drawLine(x1, y1, x2, y2);
x4 = x1;
y4 = y1;
z = false;
}
else {
g.drawLine(x3, y3, x2, y2);
}
x3 = x2;
y3 = y2;
}
當鼠標執行點擊操作時,連接點擊點的座標(x2,y2)與上面記錄的(x4,y4)
public void mouseClicked(MouseEvent e) {
int count = e.getClickCount();
if( count == 2){
if("choose13".equals(command)){
x2 = e.getX(); y2 = e.getY();
g.drawLine(x4, y4, x2, y2);
z = true;
}
}
同過鼠標按下、和釋放分別獲取座標(x1,y1)(x2,y2)並在主函數類裏定義一個全局的BufferedImage bi1 通過構造方法重載將主函數類對象傳遞到其他類,調用bi1屬性,使用機器人類對屏幕進行截圖,注意截取的位置是整個電腦屏幕的位置,所以要對座標進行相應的操作,使用表示畫圖面板區。利用重繪的方法將圖片畫到畫板上去。
else if("choose1".equals(command)){
x2 = e.getX();
y2 = e.getY();
if(p == true)
{
x3 = x1 ;
y3 = y1 ;
x4 = x2 ;
y4 = y2 ;
try{
Robot robot = new Robot();
Point point = panelCenter.getLocationOnScreen();
Rectangle rect = new Rectangle(Math.min(x1, x2)+point.x, Math.min(y1, y2)+point.y, Math.abs(x1-x2), Math.abs(y1-y2));
db.bi1 = robot.createScreenCapture(rect);
}
catch(AWTException e1){
e1.printStackTrace();
}
p = false ;
}