天天看點

swing做一個簡單的記事本(有菜單的樣式、右鍵彈出菜單、以及實作“建立”和“打開”功能)

swing做一個簡單的記事本(有菜單的樣式、右鍵彈出菜單、以及實作“建立”和“打開”功能)

1.本次記事本項目的知識總結:

①記事本的樣式是:菜單欄JMenuBar裡裝菜單JMenu,菜單裡裝菜單項JMenuItem。

②使用java内置的一些選擇對話框:例如,檔案選擇對話框JFileChooser、顔色選擇對話框JColorChooser。

swing做一個簡單的記事本(有菜單的樣式、右鍵彈出菜單、以及實作“建立”和“打開”功能)
        
swing做一個簡單的記事本(有菜單的樣式、右鍵彈出菜單、以及實作“建立”和“打開”功能)

③菜單樣式已經完成,需要實作添加事件(實作功能,例如滑鼠點選“建立”、“打開”等有不同的功能展示)。

④(由于事件越來越複雜,我們選擇封裝事件到一個外部類裡,需要用的時候再執行個體外部類。為了在外部類裡實作操作目前的窗體(控件)類,我們定義了一個窗體對象屬性,并且通過構造方法,以參數的形式,把窗體傳到外部類裡來操作。

而在窗體類裡執行個體化外部類時把自身當作參數,就可以使用外部類的操作啦,即把兩個類緊密結合起來啦):

swing做一個簡單的記事本(有菜單的樣式、右鍵彈出菜單、以及實作“建立”和“打開”功能)
      
swing做一個簡單的記事本(有菜單的樣式、右鍵彈出菜單、以及實作“建立”和“打開”功能)

⑤設定帶滾動條的文本域:

first、執行個體化文本域對象,設定實作文本能夠換行,需要設定一下文本域:通過調用文本域的.setLineWrap(true);方法。

second、再執行個體化滾動面闆的同時把文本域控件作為參數傳入,

third、 然後設定滾動面闆的垂直滾動條。

⑥外部類添加事件處理方法:這裡我們根據按鈕的文本,做出不同處理。通過事件對象的.getActionCommand()擷取按鈕的文本:

swing做一個簡單的記事本(有菜單的樣式、右鍵彈出菜單、以及實作“建立”和“打開”功能)

⑦實作右鍵彈出菜單:

first: 執行個體化右鍵彈出菜單:JpopupMenu.

second: 右鍵菜單添加菜單項:JMenuItem.

third:添加右鍵滑鼠觸發菜單事件:addMouseListener(滑鼠擴充卡對象MouseAdapter)---實作mouseClicked()方法

swing做一個簡單的記事本(有菜單的樣式、右鍵彈出菜單、以及實作“建立”和“打開”功能)

2.全部代碼:

❀記事本窗體類:

package com.xuetang9.kenny.notePaneDemo;

import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;

/**
 * 記事本類
 * 
 * @author 
 *
 */
public class NotePane extends JFrame {
    private static final String[] strMenu = { "檔案(F)", "編輯(E)", "格式(O)", "檢視(V)", "幫助(H)" }; // 菜單欄的菜單文本
    private static final String[][] strMenuItem = { { "建立", "新視窗", "打開", "儲存", "另存為", "-", "頁面設定", "列印", "-", "退出" },
            { "撤銷", "-", "複制", "剪切", "粘貼", "删除", "-", "使用bing搜尋", "查找", "查找下一個" },
            { "自動換行", "字型", null, null, null, null, null, null, null },
            { "檢視", "狀态欄", null, null, null, null, null, null, null, null },
            { "檢視幫助", "發送回報", "關于記事本", null, null, null, null, null, null, null } };
    private static final String[] strPopMenu = {"撤銷", "複制", "剪切", "粘貼", "删除", "全選", "顯示Unicode的控制字元"};
    protected JTextArea txtContent = new JTextArea();    //文本域控件
    //執行個體化外部事件類,并且把本類對象作為參數傳入
    NotePaneActionListener notePaneActionListener = new NotePaneActionListener(this);
    //右鍵彈出菜單對象
    JPopupMenu popMenu = new JPopupMenu();
    public NotePane() {
        // 構造方法實作記事本窗體的基本設定
        // 設定标題
        setTitle("記事本");
        // 設定退出模式
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        // 設定窗體大小
        setSize(800, 600);
        // 居中
        setLocationRelativeTo(null);
        // 其餘初始化工作封裝到initComponnets方法
        initComponnets();
        // 事件方法
        initEvent();
        //為了酷一點再添加右鍵彈出菜單,右鍵彈出菜單的初始化工作
        initPopMenu();    
    }
    /**
     * 為了酷一點再添加右鍵彈出菜單
     */
    private void initPopMenu() {
        //右鍵彈出菜單裡添加菜單項目
        for(String strPopMenu : strPopMenu) {
            //建立菜單項
            JMenuItem menuItem = new JMenuItem(strPopMenu);  
            //添加菜單項到彈出菜單
            this.popMenu.add(menuItem);
        }
        //文本域添加右鍵滑鼠觸發菜單事件
        txtContent.addMouseListener(new MouseAdapter() {
            //實作點選事件
             public void mouseClicked(MouseEvent e) {
                 //判斷事件是滑鼠右鍵事件
                 if(e.getButton() == MouseEvent.BUTTON3)
                 //彈出菜單
                 popMenu.show(txtContent, e.getX(), e.getY());
             }
        });
    }

    /**
     * 封裝了窗體的其餘初始化工作initComponnets方法
     */
    private void initComponnets() {
        // 1.建立菜單欄,菜單欄裡添加菜單,菜單裡添加菜單項(做出菜單的樣式)
        JMenuBar menuBar = new JMenuBar();
        // 外層循環菜單欄添加菜單,内層循環菜單添加菜單項
        for (int i = 0; i < strMenu.length; i++) {
            // 建立菜單
            JMenu menu = new JMenu(strMenu[i]);
            for (int j = 0; j < strMenuItem[i].length; j++) {
                if (null == strMenuItem[i][j]) // 如果是null
                    continue;
                if ("-".equals(strMenuItem[i][j])) { // 如果是"-",設定為分割符
                    menu.add(new JSeparator());
                } else if ("狀态欄".equals(strMenuItem[i][j])) {// 如果是"狀态欄"
                    // 添加菜單複選框項
                    JCheckBoxMenuItem checkBoxMenuItem = new JCheckBoxMenuItem(strMenuItem[i][j]);
                    menu.add(checkBoxMenuItem);
                    //添加事件
                    checkBoxMenuItem.addActionListener(notePaneActionListener);
                } else {
                    // 建立菜單項
                    JMenuItem menuItem = new JMenuItem(strMenuItem[i][j]);
                    // 菜單添加菜單項
                    menu.add(menuItem);
                    //添加事件
                    menuItem.addActionListener(notePaneActionListener);
                }
            }
            // 菜單欄添加菜單
            menuBar.add(menu);
        }
        // 窗體的菜單欄設定添加定義的菜單欄
        this.setJMenuBar(menuBar);
        //2.内容面闆添加帶滾動條的文本域
        //設定文本域,實作換行
        txtContent.setLineWrap(true);
        //建立滾動面闆
        JScrollPane scrollPane = new JScrollPane(txtContent);
        //設定滾動面闆帶有垂直滾動條
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        //内容面闆添加滾動面闆
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        
    }
    private void initEvent() {
        //2.菜單樣式做完,添加事件,由于事件複雜,選擇把事件封裝到一個外部類裡

    }
    public static void main(String[] args) {
        new NotePane().setVisible(true);
    }
}      

❀事件外部類

package com.xuetang9.kenny.notePaneDemo;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JColorChooser;
import javax.swing.JFileChooser;

/**
 * 封裝了NotePane類的事件
 * @author 
 *
 */
public class NotePaneActionListener implements ActionListener{
    //窗體對象屬性,為了在本類中操作它,同時為了與窗體類聯系起來,我們通過構造方法把窗體類對象作為參數傳入
    private NotePane notePane;
    public NotePaneActionListener(NotePane notePane) {
        this.notePane = notePane;
    }
    //書寫事件方法,ActionEvent 事件源
    @Override
    public void actionPerformed(ActionEvent e) {
        //擷取點選事件源的文本
        String strContent = e.getActionCommand();
        //也可以通過“工廠模式實作”,但是這裡我們寫的比較簡單,就直接switch結構寫啦
        switch(strContent) {
        case "建立":    //建立,就是把文本域清空
            notePane.txtContent.setText(" ");
            break;
        case "打開":    //打開顯示檔案選擇對話框,讀取使用者選擇的檔案内容到文本域,其中打開顯示檔案選擇對話框封裝成一個方法,而讀取使用者選擇的檔案内容封裝成一個工具類
            openFileChoice();
            break;
        case "字型":    //打開顯示字型顔色選擇對話框,讀取使用者選擇的顔色,修改文本域中的字型顔色
            fontColor();
            break;
        }
        
    }
    /**
     * 打開顯示字型顔色選擇對話框,讀取使用者選擇的顔色,修改文本域中的字型顔色
     */
    private void fontColor() {
        //使用java内置的顔色選擇對話框
        //建立一個顔色選擇對話框對象
        JColorChooser colorChooser = new JColorChooser(Color.ORANGE);
        //顯示顔色對話框,并且擷取使用者選擇的顔色
        Color color = colorChooser.showDialog(notePane, "請選擇顔色", Color.ORANGE);
        //修改文本域中的字型顔色
        notePane.txtContent.setForeground(color);
    }
    /**
     * 封裝打開顯示檔案選擇對話框
     * @throws IOException 
     */
    private void openFileChoice() {
        // 使用Java内置的檔案選擇對話框
        //建立一個檔案選擇對話框對象
        JFileChooser fileChooser = new JFileChooser();
        //顯示檔案選擇對話框
        fileChooser.showOpenDialog(notePane);
        //擷取使用者選擇的檔案
        File file = fileChooser.getSelectedFile();
        //讀取使用者選擇檔案的内容
        String content = null;
        try {
                content = ReadFileUtil.readContent(file.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //把讀取的内容設定到文本域
        notePane.txtContent.setText(content);
    }
    
}      

❀讀取檔案的工具類:

package com.xuetang9.kenny.notePaneDemo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

/**
 * 讀取檔案的工具類
 * 
 * @author Huangyujun
 *
 */
public class ReadFileUtil {
    /**
     * 讀取檔案内容并且傳回讀取的内容的靜态方法
     * 
     * @param path 檔案路徑
     * @return
     * @throws IOException
     */
    public static String readContent(String path) throws IOException {
        // 建立一個檔案對象
        File file = new File(path);
        // 判斷檔案是否存在
        if (!file.exists()) {
            return null;
        }
        // 定義讀取檔案内容并且傳回内容的數組
        StringBuilder content = new StringBuilder();
        // 通過字元串讀取緩存流讀取
        Reader reader = null;
        BufferedReader bufferReader = null;
        reader = new FileReader(file);
        bufferReader = new BufferedReader(reader);
        // 一行一行讀取
        String line = null;
        while ((line = bufferReader.readLine()) != null) {
            content.append(line).append(System.getProperty("line.separator"));
        }
        //關閉流
        bufferReader.close();
        reader.close();
        return content.toString();
    }
}      

3.整個項目的每部分實作:https://www.cnblogs.com/shan333/p/14564855.html    swing做一個簡單的記事本(有菜單的樣式、右鍵彈出菜單、以及實作“建立”和“打開”功能)每部分的實作

參考自:老九學堂java線上課程第十六章swing事件處理及應用《菜單--書寫記事本》