Java學(xué)習(xí)第四周總結(jié)

畫(huà)筆工具

功能

首先我們確定我們的畫(huà)筆中需要的功能:畫(huà)線條、畫(huà)等腰三角形、畫(huà)矩形、畫(huà)橢圓、顏色的選擇已經(jīng)更改、線條的加粗和變細(xì)、撤銷、清除和保存。然后我們建立一個(gè)繼承了JFrame類的子類PaintBrushFrame:
public class PaintBrushFrame extends JFrame {

    public PaintBrushFrame() {
        this.setTitle("我的繪圖工具");
        this.setSize(800, 600);
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
  }
public static void main(String[] args) {
        new PaintBrushFrame().setVisible(true);
    }
}

先創(chuàng)建出一個(gè)固定大小居中不可變的窗口,然后我們將要實(shí)現(xiàn)的功能按鈕分為兩類:1.圖形類 2.應(yīng)用類。
建立圖形抽象類:

public abstract class Shape {

    protected int startX;
    protected int startY;
    protected int endX;
    protected int endY;
    protected Color color;
    protected int lineWidth;
    
    /**
     * 畫(huà)圖
     * @param g 畫(huà)筆
     */
    public void draw(Graphics g){
        g.setColor(color);
        ((Graphics2D) g).setStroke(new BasicStroke(lineWidth));;
    }
    
    
    /**
     * 修改初始橫坐標(biāo)
     * @param startX 初始橫坐標(biāo)
     */
    public void setStartX(int startX) {
        this.startX = startX;
    }
    /**
     * 修改初始縱坐標(biāo)
     * @param startY 初始縱坐標(biāo)
     */
    public void setStartY(int startY) {
        this.startY = startY;
    }
    /**
     * 修改終點(diǎn)橫坐標(biāo)
     * @param endX 終點(diǎn)橫坐標(biāo)
     */
    public void setEndX(int endX) {
        this.endX = endX;
    }
    /**
     * 修改終點(diǎn)縱坐標(biāo)
     * @param endY 終點(diǎn)縱坐標(biāo)
     */
    public void setEndY(int endY) {
        this.endY = endY;
    }
    /**
     * 修改顏色
     * @param color 顏色
     */
    public void setColor(Color color) {
        this.color = color;
    }
    /**
     * 修改粗細(xì)
     * @param lineWidth 粗細(xì)
     */
    public void setLineWidth(int lineWidth) {
        this.lineWidth = lineWidth;
    }
    

}

建立圖形抽象類的子類線條類:

public class Line extends Shape {

    @Override
    public void draw(Graphics g) {
        super.draw(g);
        g.drawLine(startX, startY, endX, endY);
    }
}

建立圖形抽象類的子類橢圓類

public class Oval extends Shape {

    @Override
    public void draw(Graphics g) {
        super.draw(g);
        int x = startX<endX?startX:endX;
        int y = startY<endY?startY:endY;
        int width = Math.abs(startX-endX);
        int height = Math.abs(startY-endY);
        g.drawOval(x, y, width, height);
    }   
}

建立圖形抽象類的子類矩形類

public class Rectangle extends Shape {

    @Override
    public void draw(Graphics g) {
        super.draw(g);
        int x = startX<endX?startX:endX;
        int y = startY<endY?startY:endY;
        int width = Math.abs(startX-endX);
        int height = Math.abs(startY-endY);
        g.drawRect(x, y, width, height);
        
        
    }
}

建立圖形抽象類的子類等腰三角形類

public class Triangle extends Shape{

    @Override
    public void draw(Graphics g) {
        super.draw(g);
        int x1 = startX>endX?startX:endX;
        int y1 = startY>endY?startY:endY;
        int width =Math.abs(startX-endX);
        int x2 = x1 - width;
        int y2 = y1;
        int x3 = (startX<endX?startX:endX)+width/2;
        int y3 = startY <endY?startY:endY;
        g.drawPolygon(new int[] {x1, x2,x3},new int[] {y1,y2,y3},3);//畫(huà)三角形
//      g.drawLine(x1, y1, x2, y2);
//      g.drawLine(x3, y3, x2, y2);
//      g.drawLine(x1, y1, x3, y3);

        
    }

}

這個(gè)時(shí)候我們?nèi)绻獎(jiǎng)?chuàng)建圖形類的對(duì)象需要分別對(duì)這四種不同的圖形操作,這時(shí)我們可以再創(chuàng)建一個(gè)圖形的工廠類ShapeFactory,運(yùn)用多態(tài)的實(shí)現(xiàn)方法創(chuàng)建一個(gè)ShapeFactory的對(duì)象然后再對(duì)應(yīng)實(shí)現(xiàn):

public class ShapeFactory {
//靜態(tài)的東西屬于一個(gè)類,不屬于這個(gè)類的任何一個(gè)對(duì)象
    /**
     * 創(chuàng)建圖形的工廠方法
     * @param shapeType 類型
     * @return 圖形對(duì)象或null
     */
    public static Shape createShape(String shapeType){
        Shape currentShape = null;
        switch (shapeType) {
            case "矩形" :
                currentShape = new Rectangle();
                break;
            case "橢圓" :
                currentShape = new Oval();
                break;
            case "三角形":
                currentShape = new Triangle();
                break;
            case  "線條" :
                currentShape = new Line();
                break;
        }
        return currentShape;
    }
    
}

最后通過(guò)按鈕操作,鼠標(biāo)點(diǎn)擊和松開(kāi)事件的監(jiān)聽(tīng),計(jì)時(shí)器和畫(huà)筆完成:

@SuppressWarnings("serial")
public class PaintBrushFrame extends JFrame {

    private BufferedImage image = new BufferedImage(800, 600, 1);
    private List<Shape> shapesArray = new ArrayList<>();
    private String currentType = "線條";
    private Color defeultColor = Color.BLACK;
    private int defeultLineWidth = 1;

    public PaintBrushFrame() {
        this.setTitle("我的繪圖工具");
        this.setSize(800, 600);
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        JPanel buttonPanel = new JPanel();
        this.add(buttonPanel, BorderLayout.SOUTH);
        String[] buttonNames = {"線條", "矩形", "橢圓", "等腰三角形"};
        for (String name : buttonNames) {
            JButton button = new JButton(name);
            button.addActionListener(evt -> {
                currentType = evt.getActionCommand();
            });
            buttonPanel.add(button);
        }

        String[] buttonNames2 = {"選擇顏色", "-", "+", "撤銷", "清空", "保存"};
        for (String name : buttonNames2) {
            JButton button = new JButton(name);
            button.addActionListener(evt -> {
                String command = evt.getActionCommand();
                if (command.equals("選擇顏色")) {
                    Color currentColor = JColorChooser.showDialog(
                            PaintBrushFrame.this, "請(qǐng)選擇顏色", defeultColor);
                    defeultColor = currentColor != null
                            ? currentColor
                            : defeultColor;
                } else if (command.equals("-")) {
                    if (defeultLineWidth > 0) {
                        defeultLineWidth--;
                    }

                } else if (command.equals("+")) {
                    defeultLineWidth++;
                }

                else if (command.equals("撤銷")) {
                    if (!shapesArray.isEmpty()) {
                        // Java雖然擁有垃圾回收(Garbage Collection)機(jī)制
                        // 但如果程序編寫(xiě)不當(dāng)仍然有可能造成內(nèi)存泄漏
                        // 垃圾回收是針對(duì)內(nèi)存堆空間的無(wú)用對(duì)象清理工作
                        shapesArray.remove(shapesArray.size() - 1);// 防止內(nèi)存泄漏,為了讓垃圾回收器可以回收
                        repaint();
                    }

                } else if (command.equals("清空")) {
                    if (!shapesArray.isEmpty()) {
                        shapesArray.clear();
                    }
                    repaint();
                } else if (command.equals("保存")) {
                    JFileChooser chooser = new JFileChooser();
                    int choice = chooser.showSaveDialog(PaintBrushFrame.this);
                    if (choice == JFileChooser.APPROVE_OPTION) {
                        BufferedImage newImage = new BufferedImage(800, 600, 1);
                        Graphics graphics = newImage.getGraphics();
                        graphics.setColor(Color.WHITE);
                        graphics.fillRect(0, 0, 800, 600);
                        for (Shape shape : shapesArray) {
                            shape.draw(graphics);;
                        }
                        // for (int i = 0; i < totalShapes; i++) {
                        // shapesArray[i].draw(graphics);// 使用多態(tài)實(shí)現(xiàn)畫(huà)圖功能
                        // }
                        try {
                            ImageIO.write(image, "PNG",
                                    chooser.getSelectedFile());
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }

                }

            });
            buttonPanel.add(button);
        }

        /*
         * 缺省適配模式 給窗口或者窗口上的控件注冊(cè)事件監(jiān)聽(tīng)器有三種做法: 1.創(chuàng)建匿名內(nèi)部類的對(duì)象(就地實(shí)例化)
         * 2.創(chuàng)建一個(gè)內(nèi)部類對(duì)象充當(dāng)監(jiān)聽(tīng)器(因?yàn)橛忻蛛S時(shí)都可以創(chuàng)建對(duì)象) 3.讓窗口實(shí)現(xiàn)接口用窗口對(duì)象充當(dāng)監(jiān)聽(tīng)器 從Java
         * 8開(kāi)始,對(duì)于單方法接口(函數(shù)式接口)可以使用Lambda表達(dá)式 使用Lambda表達(dá)式其實(shí)就是寫(xiě)一個(gè)匿名方法來(lái)編寫(xiě)事件回調(diào)代碼
         */
        MouseAdapter adapter = new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent e) {
                int x = e.getX();
                int y = e.getY();
                // 用工廠創(chuàng)建對(duì)象(根具體的圖形類型實(shí)現(xiàn)解耦和)
                // // 畫(huà)線 Shape currentShape = new Line();//畫(huà)線
                // // Shape currentShape = new Rectangle();//畫(huà)矩形
                // // Shape currentShape = new Oval();//畫(huà)圓
                // Shape currentShape = null;
                // switch (currentType) {
                // case "矩形" :
                // currentShape = new Rectangle();
                // break;
                // case "橢圓" :
                // currentShape = new Oval();
                // break;
                // case "三角形" :
                // currentShape = new Triangle();
                // break;
                //
                // default :
                // currentShape = new Line();
                // break;
                // }
                Shape currentShape = ShapeFactory.createShape(currentType);

                currentShape.setColor(defeultColor);
                currentShape.setLineWidth(defeultLineWidth);
                currentShape.setStartX(x);
                currentShape.setStartY(y);
                currentShape.setEndX(x);
                currentShape.setEndY(y);
                shapesArray.add(currentShape);
            }

            @Override
            public void mouseDragged(MouseEvent e) {
                Shape currentShape = shapesArray.get(shapesArray.size() - 1);
                int x = e.getX();
                int y = e.getY();
                currentShape.setEndX(x);
                currentShape.setEndY(y);
                repaint();
            }
        };
        this.addMouseListener(adapter);
        this.addMouseMotionListener(adapter);

        // currentShape.setStartX(50);
        // currentShape.setStartY(80);
        // currentShape.setEndX(500);
        // currentShape.setEndY(380);

    }

    // 該方法為回調(diào)方法
    @Override
    public void paint(Graphics g) {
        Graphics otherGraphics = image.getGraphics();
        super.paint(otherGraphics);
        for (Shape shape : shapesArray) {
            shape.draw(otherGraphics);
        }
        g.drawImage(image, 0, 0, null);

    }

    public static void main(String[] args) {
        new PaintBrushFrame().setVisible(true);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,908評(píng)論 6 541
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,324評(píng)論 3 429
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事。” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 178,018評(píng)論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 63,675評(píng)論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,417評(píng)論 6 412
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 55,783評(píng)論 1 329
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,779評(píng)論 3 446
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 42,960評(píng)論 0 290
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,522評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,267評(píng)論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,471評(píng)論 1 374
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,009評(píng)論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,698評(píng)論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 35,099評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 36,386評(píng)論 1 294
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,204評(píng)論 3 398
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,436評(píng)論 2 378

推薦閱讀更多精彩內(nèi)容

  • 1.import static是Java 5增加的功能,就是將Import類中的靜態(tài)方法,可以作為本類的靜態(tài)方法來(lái)...
    XLsn0w閱讀 1,258評(píng)論 0 2
  • 面向?qū)ο笾饕槍?duì)面向過(guò)程。 面向過(guò)程的基本單元是函數(shù)。 什么是對(duì)象:EVERYTHING IS OBJECT(萬(wàn)物...
    sinpi閱讀 1,079評(píng)論 0 4
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,716評(píng)論 25 708
  • 態(tài)度 像風(fēng)一樣愛(ài)這顆星球 像石頭一樣對(duì)時(shí)間保持耐心 像雨一樣憐憫萬(wàn)物 然后做一片土地把世界的心抱在懷里 不安 心中...
    未禾一閱讀 149評(píng)論 0 0
  • 第一次乘坐南航的飛機(jī),居然看了兩遍同一個(gè)電影。耳機(jī)很不好用,看著中文字幕,居然斷斷續(xù)續(xù)的看完了這部讓我感到憂傷還有...
    薄帷鑒明月閱讀 8,616評(píng)論 0 1