1. 程式人生 > >Java實現簡易的記事本

Java實現簡易的記事本


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;


import javax.swing.*;
import javax.swing.plaf.basic.BasicBorders.RadioButtonBorder;


/**
 * 簡易編輯器V1,0
 * 
 * @author CGgeeker
 * 
 */
public class Editor02 extends JFrame implements ActionListener {
JComboBox comboBoxOfFontName, comboBoxOfFontsize;
JTextArea textArea;
JCheckBox checkBoxOfFontStylebold, checkBoxOfFontStyleitalic;
JRadioButton radiobuttonred, radiobuttonblue, radiobuttongreen;
ButtonGroup buttongroupcolor;
JPanel panelcolor;
Clipboard clipboard = getToolkit().getSystemClipboard();


public Editor02() {
// 設定窗體標題
super("簡易編輯器V2.0");
// 獲取螢幕解析度
Dimension dim = this.getToolkit().getScreenSize();
// 窗體初始大小及定位
this.setBounds(dim.width / 4, dim.height / 4, (dim.width / 2 + 40),dim.height / 2);
// 設定內容面板按邊界佈局
this.getContentPane().setLayout(new BorderLayout());
// 1. 呼叫自定義方法addMenuBar()設定窗體的選單欄
this.addMenuBar();
// 2. 呼叫自定義方法addToolBar()新增工具欄到內容面板
this.addToolBar();
// 3. 呼叫自定義方法addTextArea()新增文字區到內容面板
this.addTextArea();
}


/**
* 設定窗體選單欄
*/
private void addMenuBar() {
// 建立選單欄
JMenuBar menuBar = new JMenuBar();
// 建立“檔案”選單
JMenu filemenu = new JMenu("檔案");
// 建立“編輯”選單
JMenu editormenu = new JMenu("編輯");
// 建立“幫助”選單
JMenu helpmenu = new JMenu("幫助");
// 建立選單項
JMenuItem menuItemOfOpen = new JMenuItem("開啟");
JMenuItem menuItemOfSave = new JMenuItem("儲存");
JMenuItem menuItemOfExit = new JMenuItem("退出");
JMenuItem menuItemOfCopy = new JMenuItem("複製");
JMenuItem menuItemOfCut = new JMenuItem("剪下");
JMenuItem menuItemOfPaste = new JMenuItem("貼上");
JMenuItem menuItemOfDelete = new JMenuItem("刪除");
JMenuItem menuItemOfHelpexplanation = new JMenuItem("幫助說明");
// 給各個選單項註冊單擊事件偵聽器
menuItemOfOpen.addActionListener(this);
menuItemOfSave.addActionListener(this);
menuItemOfExit.addActionListener(this);
menuItemOfCopy.addActionListener(this);
menuItemOfCut.addActionListener(this);
menuItemOfPaste.addActionListener(this);
menuItemOfDelete.addActionListener(this);
menuItemOfHelpexplanation.addActionListener(new ActionListener() {
/**
* 幫助窗體(彈窗)
*/
@Override
public void actionPerformed(ActionEvent e) {
String separator = System.getProperty("line.separator");// 獲得系統預設的分隔符-固定寫法(寫死了的!)
final JFrame helpjframe = new JFrame("幫助說明");
helpjframe.setBounds(410, 250, 600, 320);
helpjframe.setVisible(true);
helpjframe.setLayout(new BorderLayout());
TextArea helpjframetextArea = new TextArea();
helpjframetextArea.setText("該文字功能如下:" + separator + separator
+ "1.實現基本的TXT檔案儲存和開啟" + separator + separator
+ "2.實現基本的剪輯,複製,貼上,刪除功能" + separator + separator
+ "3.實現基本的字型處理操作!");
helpjframetextArea.setForeground(getForeground().blue); // 設定前景色(字型的顏色)
helpjframetextArea.setFont(new Font(null, HEIGHT, 26)); // 設定字型大小,樣式
JButton helpjframeButton = new JButton("退出");

helpjframe.add(helpjframetextArea);
helpjframe.add(helpjframeButton);

helpjframe.add(helpjframetextArea, "Center"); // 簡單佈局
helpjframe.add(helpjframeButton, "South");
helpjframeButton.addActionListener(new ActionListener() {
// 實現對“幫助說明”窗體中的“退出”按鈕的監聽事件處理
@Override
public void actionPerformed(ActionEvent e) {
if (JOptionPane.showConfirmDialog(helpjframe, "是否退出?") == 0) {
helpjframe.setVisible(false);
}
}
});
}
});
// 給文字域新增滑鼠監聽器

// 選單項加到"檔案"選單
filemenu.add(menuItemOfOpen);
filemenu.add(menuItemOfSave);
filemenu.addSeparator(); // 新增分隔線
filemenu.add(menuItemOfExit);
// 選單項加到"編輯"選單
editormenu.add(menuItemOfCopy);
editormenu.add(menuItemOfCut);
editormenu.add(menuItemOfPaste);
editormenu.add(menuItemOfDelete);
// 選單項新增到"幫助"選單
helpmenu.add(menuItemOfHelpexplanation);
// 將"檔案"選單,"編輯"選單,"幫助"選單加到選單欄
menuBar.add(filemenu);
menuBar.add(editormenu);
menuBar.add(helpmenu);
// 設定窗體的選單欄
this.setJMenuBar(menuBar);
}
/**
* 新增工具欄
*/
private void addToolBar() {
// 建立工具欄
JToolBar toolBar = new JToolBar();
// 設定工具欄的佈局
toolBar.setLayout(new FlowLayout(FlowLayout.LEFT));
// 獲取系統字型名字
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String fontNames[] = ge.getAvailableFontFamilyNames();
// 設定文字大小陣列
String fontsizeNames[] = { "20", "23", "26", "29", "32", "35", "38","42" };
// 建立“字型”標籤
Label fontlabel = new Label("字型:");
// 建立“大小”標籤
Label fontsizelabel = new Label("大小:");
// 建立“風格”標籤
Label fontstyle = new Label("風格:");
// 建立“顏色”標籤
Label fontcolor = new Label("顏色:");
// 建立字型組合框
comboBoxOfFontName = new JComboBox(fontNames);
// 建立字型大小組合框
comboBoxOfFontsize = new JComboBox(fontsizeNames);
// 建立字型風格複選框
checkBoxOfFontStylebold = new JCheckBox("粗體");
checkBoxOfFontStyleitalic = new JCheckBox("斜體");
// 建立顏色面板
panelcolor = new JPanel();
// 建立顏色按鈕組
buttongroupcolor = new ButtonGroup();
// 建立字型顏色單選按鈕
radiobuttonred = new JRadioButton("紅");
radiobuttonblue = new JRadioButton("藍");
radiobuttongreen = new JRadioButton("綠");
// 字型組合框註冊單擊事件偵聽器
comboBoxOfFontName.addActionListener(this);
// 字型大小組合框註冊單擊事件監聽器
comboBoxOfFontsize.addActionListener(this);
// 給複選框註冊單擊事件監聽器
checkBoxOfFontStylebold.addActionListener(this);
checkBoxOfFontStyleitalic.addActionListener(this);
// 給單選按鈕註冊單擊事件監聽器
radiobuttonred.addActionListener(this);
radiobuttonblue.addActionListener(this);
radiobuttongreen.addActionListener(this);
// 在字型組合框中新增“字型”標籤
toolBar.add(fontlabel);
// 字型組合框加到工具欄
toolBar.add(comboBoxOfFontName);
// 在字型大小組合框中加“大小”標籤
toolBar.add(fontsizelabel);
// 字型大小組合框加到工具欄
toolBar.add(comboBoxOfFontsize);
// 給複選框新增“風格”標籤
toolBar.add(fontstyle);
// 字型風格複選框加到工具欄
toolBar.add(checkBoxOfFontStylebold);
toolBar.add(checkBoxOfFontStyleitalic);
// 給單選框新增“顏色”標籤
toolBar.add(fontcolor);
// 字型顏色單選按鈕加到顏色按鈕組中
buttongroupcolor.add(radiobuttonred);
buttongroupcolor.add(radiobuttonblue);
buttongroupcolor.add(radiobuttongreen);
// 往面板中加入單選按鈕
panelcolor.add(radiobuttonred);
panelcolor.add(radiobuttonblue);
panelcolor.add(radiobuttongreen);
// 顏色按鈕組加到工具欄
toolBar.add(panelcolor);
// 工具欄加到內容面板北邊
this.getContentPane().add(toolBar, "North");
}


/**
* 新增文字區
*/
private void addTextArea() {
textArea = new JTextArea("歡迎來到我的世界,上帝你好!");
textArea.setLineWrap(true); // 設定文字域為自動換行
textArea.setBackground(getBackground().pink); // 給文字域設定背景顏色為粉紅
JScrollPane textareascrollPane = new JScrollPane(textArea); // 將文字域新增到含有下拉框(條)的面板中
this.getContentPane().add(textareascrollPane); // 將含有下拉框的面板放入內容面板中
this.getContentPane().add(textareascrollPane, "Center"); // 完成下拉框面板在內容面板中的邊界佈局,居中
// 設定下拉框面板的下拉條總是可見
textareascrollPane.setVerticalScrollBarPolicy(textareascrollPane.VERTICAL_SCROLLBAR_ALWAYS);
}


/*
* 單擊事件處理
*/
@Override
public void actionPerformed(ActionEvent e) {
// 獲取文字區的字型
Font font = textArea.getFont();
int fontStyle = font.getStyle();
int fontSize = font.getSize();
String fontName = font.getName();
// 判斷是否點選了“檔案”選單
if (e.getSource() instanceof JMenuItem) {
// 處理開啟檔案事件
if (e.getActionCommand() == "開啟") {
// System.out.println("open !"); //該語句用於設計師的測試
Openfile();
}
// 處理儲存檔案事件
if (e.getActionCommand() == "儲存") {
// System.out.println("save !"); //該語句用於設計師的測試
Savefile();
}
// 點選退出就退出程式
if (e.getActionCommand() == "退出") {
// System.out.println("exit !"); //該語句用於設計師的測試
Exiteditor();
}
}
// 判斷是否點選了“編輯”選單
if (e.getSource() instanceof JMenuItem) {
// 處理複製事件
if (e.getActionCommand() == "複製") {
String tempText = textArea.getSelectedText(); // 拖動滑鼠選取文字
// 建立能傳輸指定 String 的 Transferable。
StringSelection editText = new StringSelection(tempText);
/*
* 將剪貼簿的當前內容設定到指定的 transferable 物件, 並將指定的剪貼簿所有者作為新內容的所有者註冊。
*/
clipboard.setContents(editText, null);
return;
}
// 處理貼上事件
if (e.getActionCommand() == "貼上") {
// textArea.paste();
// System.out.println("1234"); 測試資料
int start = textArea.getSelectionStart();
int end = textArea.getSelectionEnd();
Transferable contents = clipboard.getContents(this);
DataFlavor flavor = DataFlavor.stringFlavor;
if (contents.isDataFlavorSupported(flavor)) {
try {
String str;
str = (String) contents.getTransferData(flavor);
// System.out.println(str); 測試資料
textArea.replaceRange(str, start, end);
} catch (Exception ex) {
ex.printStackTrace();
}
}
// setSysClipboardText("");
return;
}
// 處理刪除事件
if (e.getActionCommand() == "刪除") {
int start = textArea.getSelectionStart();
int end = textArea.getSelectionEnd();
textArea.replaceRange("", start, end);
return;
}
// 處理剪下事件
if (e.getActionCommand() == "剪下") {
String tempText = textArea.getSelectedText();
StringSelection editText = new StringSelection(tempText);
clipboard.setContents(editText, null);
int start = textArea.getSelectionStart();
int end = textArea.getSelectionEnd();
textArea.replaceRange("", start, end); // 從Text1中刪除被選取的文字。
return;
}
}
//對字型風格和文字大小的處理
if (e.getSource() instanceof JComboBox) {
//處理文字大小
if (e.getSource().equals(comboBoxOfFontsize)) {
// 獲取字型大小組合選中字型大小
// fontSize = (int) comboBoxOfFontsize.getSelectedItem();
String fontSize2;
fontSize2 = (String) comboBoxOfFontsize.getSelectedItem();
// 修改文字區字型
textArea.setFont(new Font(fontName, fontStyle, Integer.parseInt(fontSize2)));
}
//處理字型風格
if (e.getSource().equals(comboBoxOfFontName)) {
// 獲取字型組合選中字型名
fontName = (String) comboBoxOfFontName.getSelectedItem();
// 修改文字區字型
textArea.setFont(new Font(fontName, fontStyle, fontSize));
}
}
//對文字進行加粗或者還原處理
if (e.getSource().equals(checkBoxOfFontStylebold)) {
fontStyle = fontStyle ^ 1; // ^ 異或運算 (加粗:和1做異或運算)
textArea.setFont(new Font(fontName, fontStyle, fontSize));
}
//對文字進行傾斜或者還原處理
if (e.getSource().equals(checkBoxOfFontStyleitalic)) {
fontStyle = fontStyle ^ 2; // (斜體:和2做異或運算)
textArea.setFont(new Font(fontName, fontStyle, fontSize));
}
/*
* 對文字進行變色處理
*/
if (e.getSource().equals(radiobuttonred)) {
textArea.setForeground(Color.red);
}


if (e.getSource().equals(radiobuttonblue)) {
textArea.setForeground(Color.blue);
}


if (e.getSource().equals(radiobuttongreen)) {
textArea.setForeground(Color.green);
}
}
/**
*對系統的剪輯板進行覆蓋的方法
*/
public static void setSysClipboardText(String writeMe) {
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable tText = new StringSelection(writeMe); // 覆蓋系統剪下板
clip.setContents(tText, null);
}
/**
* 開啟檔案方法封裝
*/
public void Openfile() {
JFileChooser fileChooser = new JFileChooser("d:\\");
// fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// 這句用於硬性規定只能選擇資料夾,而不能選擇檔案
int returnVal = fileChooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) { // 如果選擇了對話方塊中的確定按鈕,就執行以下操作
File openfilePath = fileChooser.getSelectedFile();// 這個就是你選擇的資料夾的路徑
try { // 流操作
FileInputStream input = new FileInputStream(openfilePath); // FileInputStream檔案輸入流,將檔案資料讀出來
BufferedReader breader = new BufferedReader(new InputStreamReader(input)); // BufferedReader字元輸入流提高讀出速率
String tempreader = "";
while ((tempreader = breader.readLine()) != null) { // 將讀出的資料一行一行地寫入程式(文字編輯器)的文字域中
textArea.append(tempreader);
}
breader.close(); // 關閉字元輸入流
input.close(); // 關閉檔案輸入流
} catch (FileNotFoundException e1) { // 異常處理
e1.printStackTrace(); // printStackTrace()方法的意思是:在命令列列印異常資訊在程式中出錯的位置及原因。
} catch (IOException e1) {
e1.printStackTrace(); // printStackTrace()方法的意思是:在命令列列印異常資訊在程式中出錯的位置及原因。
}
} else {
// 由於系統自己有取消的方法所以這裡就不擴充了!
}
}
/**
* 儲存檔案方法封裝
*/
public void Savefile() {
File savefilePath = new File("D:/javaeditortest/editor.txt"); // 儲存檔案的路徑
try {
FileOutputStream output = new FileOutputStream(savefilePath); // FileOutputStream檔案輸出流,將資料寫入檔案
BufferedWriter bwriter = new BufferedWriter(new OutputStreamWriter(output)); // BufferedWriter字元輸出流提高寫入速率
for (String textareatemp : textArea.getText().split("\n")) { // 遍歷,此處的textArea.getText().split("\n")可以當做一個數組,讓後遍歷處理,加上換行處理
bwriter.write(textareatemp); // 將文字域的內容寫入檔案中
bwriter.newLine();// 換行
}
bwriter.flush(); // 重新整理字元輸出流通道
bwriter.close(); // 關閉字元輸出流
output.close(); // 關閉檔案輸出流
JOptionPane.showMessageDialog(null, "已經儲存成功啦!");
} catch (FileNotFoundException e) {
e.printStackTrace(); // printStackTrace()方法的意思是:在命令列列印異常資訊在程式中出錯的位置及原因。
} catch (IOException e) {
e.printStackTrace(); // printStackTrace()方法的意思是:在命令列列印異常資訊在程式中出錯的位置及原因。
}
}
/**
* 退出文字編輯器的方法封裝
*/
public void Exiteditor() {
if (JOptionPane.showConfirmDialog(this, "退出系統?") == 0) {
System.exit(0);
}
}
public static void main(String[] args) {
Editor02 editor = new Editor02();
editor.setVisible(true);
}
}