文本編輯器EditPlus

程序運行圖片:

/**
 * @author 廖俊瑤
 */
package editPlus;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.UIManager;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

@SuppressWarnings("serial")
public class EditPlus extends JFrame implements ActionListener {
	// 定義變量
	private JMenuBar jmb;// 菜單條
	private JMenu jmfile, jmedit, jmhelp;// 菜單
	private JMenuItem jmtabout, jmtfiles[], jmtedits[];// 菜單項
	private JMenuItem popMenuItems[];
	private JToolBar jtb;// 工具條
	private JTextArea jta;// 文本域
	private JPopupMenu popmenu;// 彈出式菜單
	@SuppressWarnings("rawtypes")
	private JComboBox jcbfont, jcbsize;// 組合框
	private JColorChooser jcc;// 顏色選擇框
	private JButton fontcolor, clearall;// 按鈕
	private Color color;// 顏色
	private Font menufont, font;// 字體
	private JLabel jlfont, jlsize, jlstyle, jlcolor, jlstastic;// 標籤
	private JCheckBox jcbbold, jcbitalic;// 複選框
	private JCheckBoxMenuItem jmtlinewrap;// 複選菜單項
	private JPanel p1, p2, p3;
	private Dimension dim;
	private JFileChooser jfc;
	private FileWriter fw;
	private FileReader fr;
	private String path, time;
	private int stastic;
	private boolean isSaved = false, isUpdated = false;

	// 構造函數
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public EditPlus() {
		super("Edit++");// 設置窗口標題
		menufont = new Font("微軟雅黑", Font.PLAIN, 14);// UI字體
		dim = this.getToolkit().getScreenSize();// 獲取屏幕分辨率
		jmb = new JMenuBar();
		this.setUIFont();// 把各組件的字體設置爲menufont
		this.setSize(dim.width * 2 / 3, dim.height * 2 / 3);// 設置窗口大小
		this.setJMenuBar(jmb);
		// 創建菜單
		jmfile = new JMenu("文件");
		jmedit = new JMenu("編輯");
		jmhelp = new JMenu("幫助");
		// 創建菜單項
		String[] jmfileStr = { "新建", "打開", "保存", "另存爲", "退出" };
		jmtfiles = new JMenuItem[jmfileStr.length];
		for (int i = 0; i < jmfileStr.length; i++) {
			jmtfiles[i] = new JMenuItem(jmfileStr[i]);
			jmtfiles[i].addActionListener(this);
			jmfile.add(jmtfiles[i]);
			if (i == 3) {
				jmfile.addSeparator();
			}
		}
		jmtfiles[2].setEnabled(false);
		String[] jmeditStr = { "撤銷", "剪切 Ctrl+X", "複製 Ctrl+C", "粘貼 Ctrl+V",
				"時間", "清空文本", "查找" };
		jmtedits = new JMenuItem[jmeditStr.length];
		for (int i = 0; i < jmeditStr.length; i++) {
			jmtedits[i] = new JMenuItem(jmeditStr[i]);
			jmtedits[i].addActionListener(this);
			jmedit.add(jmtedits[i]);
			if (i == 3 || i == 4) {
				jmedit.addSeparator();
			}
		}
		jmtlinewrap = new JCheckBoxMenuItem("自動換行");
		jmtabout = new JMenuItem("關於");

		// 給菜單項添加ActionListener監聽器
		jmtlinewrap.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (jmtlinewrap.isSelected()) {
					jta.setLineWrap(true);// 設置爲自動換行
				} else {
					jta.setLineWrap(false);// 設置爲不自動換行
				}
			}
		});
		jmtabout.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (e.getSource() == jmtabout) {// “關於”信息
					JOptionPane.showMessageDialog(EditPlus.this,
							"Edit++\n版本:1.0 預覽版\nDesigned by LJY\nPowered by Java",
							"關於", JOptionPane.INFORMATION_MESSAGE);
				}
			}
		});

		// 將菜單添加到菜單欄中
		jmb.add(jmfile);
		jmb.add(jmedit);
		jmb.add(jmhelp);
		jmedit.add(jmtlinewrap);
		jmhelp.add(jmtabout);

		// 創建JToolBar
		jtb = new JToolBar();
		jtb.setLayout(new FlowLayout(FlowLayout.LEFT));

		// 創建JTextArea
		jta = new JTextArea();
		jta.setFont(new Font("微軟雅黑", Font.PLAIN, 16));// 設置初始字體
		font = jta.getFont();
		jta.addMouseListener(new MouseListener() {
			@Override
			// 鼠標單擊事件
			public void mouseClicked(MouseEvent e) {
				if (e.getModifiers() == MouseEvent.BUTTON3_MASK) {
					popmenu.show(jta, e.getX(), e.getY());// 鼠標右鍵在文本域中單擊,彈出菜單
				}
			}

			@SuppressWarnings("deprecation")
			@Override
			public void mouseEntered(MouseEvent e) {
				EditPlus.this.setCursor(Cursor.CROSSHAIR_CURSOR);// 設置鼠標樣式爲文本編輯樣式
			}

			@SuppressWarnings("deprecation")
			@Override
			public void mouseExited(MouseEvent e) {
				EditPlus.this.setCursor(Cursor.DEFAULT_CURSOR);// 設置鼠標樣式爲默認樣式
			}

			@Override
			public void mouseReleased(MouseEvent e) {
			}

			@Override
			public void mousePressed(MouseEvent e) {
			}
		});
		jta.addCaretListener(new CaretListener() {
			@Override
			public void caretUpdate(CaretEvent e) {
				isUpdated = true;
				stastic = jta.getText().trim().toString().length();// 除去空格和換行符都計數
				jlstastic.setText("字數:" + stastic);
				// TODO

			}
		});

		// 創建面板1
		GraphicsEnvironment ge = GraphicsEnvironment
				.getLocalGraphicsEnvironment();// 獲取本地繪圖環境
		String[] fontsName = ge.getAvailableFontFamilyNames();// 獲取系統中的字體
		p1 = new JPanel();
		jlfont = new JLabel("字體: ");
		jcbfont = new JComboBox<Object>(fontsName);
		p1.setOpaque(false);// 設置面板變透明
//		jcbfont.setSelectedIndex(260);// 默認選中微軟雅黑
		jcbfont.addActionListener(this);
		p1.add(jlfont);
		p1.add(jcbfont);
		jtb.add(p1);

		// 創建面板2
		p2 = new JPanel();
		String sizeStr[] = new String[60];
		for (int i = 0; i < 60; i++) {
			sizeStr[i] = String.valueOf(i + 1);
		}
		jlsize = new JLabel(" 字號:");
		jcbsize = new JComboBox(sizeStr);
		p2.setOpaque(false);
		p2.add(jlsize);
		jcbsize.setEditable(false);
		jcbsize.setSelectedIndex(15);// 設置默認選中項爲第15項
		jcbsize.setEditable(false);
		jcbsize.addActionListener(this);
		p2.add(jcbsize);
		jtb.add(p2);

		// 創建面板3
		p3 = new JPanel();
		fontcolor = new JButton("字體顏色");
		jcbbold = new JCheckBox("粗體");
		jcbitalic = new JCheckBox("斜體");
		jlstyle = new JLabel(" 字型 :");
		jlcolor = new JLabel(" ●﹏● ");
		clearall = new JButton("清空文本");
		p3.setOpaque(false);// 設置面板爲透明
		jcbitalic.setOpaque(false);
		jcbbold.setOpaque(false);
		fontcolor.setForeground(color);
		fontcolor.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (e.getSource() == fontcolor) {// 設置字體顏色事件
					jcc = new JColorChooser();
					color = JColorChooser.showDialog(EditPlus.this, "選擇字體顏色",
							color);
					jta.setForeground(color);// 設置文本域的顏色
					jlcolor.setForeground(color);// 顯示字體的顏色
				}
			}
		});// 添加ActionListener監聽器
		jcbbold.addActionListener(this);
		jcbitalic.addActionListener(this);
		clearall.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (e.getSource() == jmtedits[5] || e.getSource() == clearall) {// "清空"事件
					jta.setText("");
				}
			}
		});
		p3.add(fontcolor);
		p3.add(jlcolor);
		p3.add(jlstyle);
		p3.add(jcbbold);
		p3.add(jcbitalic);
		p3.add(clearall);
		jtb.add(p3);
		this.getContentPane().add(jtb, "North");// 把JToolBar添加到面板的北邊

		// 創建統計字數的JLabel
		jlstastic = new JLabel("字數:" + stastic);
		jlstastic.setBackground(Color.WHITE);
		jlstastic.setOpaque(true);
		this.getContentPane().add(jlstastic, "South");

		// 創建JPopupMenu
		popmenu = new JPopupMenu();
		String menuItemStrs[] = { "剪切 Ctrl+X", "複製 Ctrl+C", "粘貼 Ctrl+V" };
		popMenuItems = new JMenuItem[menuItemStrs.length];
		for (int i = 0; i < popMenuItems.length; i++) {
			popMenuItems[i] = new JMenuItem(menuItemStrs[i]);
			popmenu.add(popMenuItems[i]);
			if (i == 1) {
				popmenu.addSeparator();
			}
			popMenuItems[i].addActionListener(this);
		}
		jta.add(popmenu);
		this.addWindowListener(new WindowListener() {
			@Override
			public void windowClosing(WindowEvent e) {
				if (isSaved == false && isUpdated) {
					if (JOptionPane.showConfirmDialog(EditPlus.this,
							"文件尚未保存,需要保存嗎?", "提示", JOptionPane.YES_NO_OPTION,
							JOptionPane.INFORMATION_MESSAGE) == JOptionPane.OK_OPTION) {
						saveFileAs();
					}
				}
				if (JOptionPane.showConfirmDialog(EditPlus.this,
						"確定要提出Edit++嗎?", "退出", JOptionPane.YES_NO_OPTION,
						JOptionPane.INFORMATION_MESSAGE) == JOptionPane.OK_OPTION) {
					System.exit(0);
				} else {
					EditPlus.this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
				}
			}

			@Override
			public void windowOpened(WindowEvent e) {
			}

			@Override
			public void windowClosed(WindowEvent e) {
			}

			@Override
			public void windowIconified(WindowEvent e) {
			}

			@Override
			public void windowDeiconified(WindowEvent e) {
			}

			@Override
			public void windowActivated(WindowEvent e) {
			}

			@Override
			public void windowDeactivated(WindowEvent e) {
			}
		});
		this.getContentPane().add(new JScrollPane(jta));// 添加帶滾動條的JTextArea
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setVisible(true);
	}

	@Override
	// ActionListener事件
	public void actionPerformed(ActionEvent e) {
		String fontName = jcbfont.getSelectedItem().toString();
		int size = Integer.parseInt(jcbsize.getSelectedItem().toString());
		int style = font.getStyle();// 獲取字體風格
		if (jcbbold.isSelected()) {
			style ^= 1;// 只改倒數第一個二進制位即表示是否粗體的數據信息
		}
		if (jcbitalic.isSelected()) {
			style ^= 2;// 只改倒數第二個二進制位即表示是否斜體的數據信息
		}
		jta.setFont(new Font(fontName, style, size));
		if (e.getSource() == jmtfiles[0]) {// “新建”事件
			newFile();
		}
		if (e.getSource() == jmtfiles[1]) {// “打開”事件
			openFile();
		}
		if (e.getSource() == jmtfiles[2]) {// "保存“事件
			saveFile();
		}
		if (e.getSource() == jmtfiles[3]) {// "另存爲“事件
			saveFileAs();
		}
		if (e.getSource() == jmtfiles[4]) {// “退出”事件
			if (isSaved == false && isUpdated) {
				if (JOptionPane.showConfirmDialog(this, "文件尚未保存,需要保存嗎?", "提示",
						JOptionPane.YES_NO_OPTION,
						JOptionPane.INFORMATION_MESSAGE) == JOptionPane.OK_OPTION) {
					saveFileAs();
				}
			}
			if (JOptionPane.showConfirmDialog(this, "確定要提出Edit++嗎?", "退出",
					JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE) == JOptionPane.OK_OPTION) {
				System.exit(0);
			}
		}
		if (e.getSource() == jmtedits[0]) {// "撤銷“事件
			// TODO
		}
		if (e.getSource() == jmtedits[4]) {// "時間“事件
			setTime();
		}
		if (e.getSource() == jmtedits[6]) {// "查找"事件
			new WordSearch();
		}

		if (e.getSource() == popMenuItems[0] || e.getSource() == jmtedits[1]) {// 剪切按鈕
			jta.cut();
		}
		if (e.getSource() == popMenuItems[1] || e.getSource() == jmtedits[2]) {// 複製按鈕
			jta.copy();
		}
		if (e.getSource() == popMenuItems[2] || e.getSource() == jmtedits[3]) {// 粘貼按鈕
			jta.paste();
		}
	}

	public void newFile() {
		try {
			jfc = new JFileChooser();
			jfc.showDialog(this, "新建");
			path = jfc.getSelectedFile().getAbsolutePath() + ".txt";
			fw = new FileWriter(path);
			jmtfiles[2].setEnabled(true);
		} catch (IOException e1) {
			JOptionPane.showMessageDialog(this, "文件新建錯誤");
		} catch (Exception e2) {
		}
	}

	public void openFile() {
		fr = null;
		char[] buffer = new char[1024];
		String str = null;
		int num = 0;
		try {
			jfc = new JFileChooser();
			jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
			jfc.showOpenDialog(this);
			fr = new FileReader(jfc.getSelectedFile().getAbsolutePath());
			do {
				num = fr.read(buffer);
				for (int i = 0; i < num; i++) {
					str += buffer[i] + "";
				}
				jta.setText(str);
			} while (num > 0);
		} catch (FileNotFoundException e1) {
			JOptionPane.showMessageDialog(this, "找不到該文件");
		} catch (IOException e1) {
			JOptionPane.showMessageDialog(this, "文件讀取錯誤");
		} catch (Exception e2) {
		} finally {
			try {
				fr.close();
			} catch (IOException e1) {
				JOptionPane.showMessageDialog(this, "文件無法關閉");
			} catch (Exception e2) {
			}
		}
	}

	public void saveFile() {
		try {
			fw = new FileWriter(path);
			fw.write(jta.getText());
			isSaved = true;
		} catch (IOException e1) {
			JOptionPane.showMessageDialog(this, "文件保存錯誤");
		} catch (Exception e) {
		} finally {
			try {
				fw.close();
			} catch (IOException e1) {
				JOptionPane.showMessageDialog(this, "文件無法關閉");
			} catch (Exception e2) {
			}
		}
	}

	public void saveFileAs() {
		try {
			jfc = new JFileChooser();
			jfc.showDialog(this, "另存爲");
			fw = new FileWriter(jfc.getSelectedFile().getAbsolutePath()
					+ ".txt");
			fw.write(jta.getText());
			isSaved = true;
		} catch (IOException e1) {
			JOptionPane.showMessageDialog(this, "文件保存錯誤");
		} catch (Exception e) {
		} finally {
			try {
				fw.close();
			} catch (IOException e1) {
				JOptionPane.showMessageDialog(this, "文件無法關閉");
			} catch (Exception e2) {
			}
		}
	}

	public void setUIFont() {
		try {
			String lookAndFeel = UIManager.getSystemLookAndFeelClassName();// 獲取系統外觀樣式
			UIManager.setLookAndFeel(lookAndFeel);// 設置程序外觀樣式爲系統樣式
		} catch (Exception e) {
			JOptionPane.showMessageDialog(this, "獲取系統外觀樣式失敗,將使用默認樣式");
		}
		UIManager.put("OptionPane.font", menufont);
		UIManager.put("OptionPane.messageFont", menufont);
		UIManager.put("OptionPane.buttonFont", menufont);
		UIManager.put("MenuBar.font", menufont);
		UIManager.put("MenuItem.font", menufont);
		UIManager.put("Menu.font", menufont);
		UIManager.put("PopupMenu.font", menufont);
		UIManager.put("ToolBar.font", menufont);
		UIManager.put("ComboBox.font", menufont);
		UIManager.put("Button.font", menufont);
		UIManager.put("CheckBox.font", menufont);
		UIManager.put("CheckBoxMenuItem.font", menufont);
		UIManager.put("Dialog.font", menufont);
		UIManager.put("Panel.font", menufont);
		UIManager.put("Label.font", menufont);
	}

	public void setTime() {
		Date date = new Date();
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		time = sdf.format(date);
		if (jta.getText().equals("")) {
			jta.setText(jta.getText() + time);
		} else {
			jta.setText(jta.getText() + "\n" + time);
		}
	}

	// 內部類:搜索模塊
	class WordSearch extends JFrame {
		private Dimension dim;
		private JPanel p1, p2, p3;
		private JLabel search, replace;
		private JTextField jtf1, jtf2;
		private JButton confirm;
		private String source, target;

		public WordSearch() {
			super("查找/替換");
			dim = this.getToolkit().getScreenSize();
			this.setSize(dim.width / 5, dim.height / 5);
			this.setLayout(new GridLayout(3, 1));
			p1 = new JPanel();
			p2 = new JPanel();
			p3 = new JPanel();
			search = new JLabel("查找:");
			replace = new JLabel("替換:");
			jtf1 = new JTextField(30);
			jtf2 = new JTextField(30);
			confirm = new JButton("確定");
			confirm.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					source = jtf1.getText();
					target = jtf2.getText();
					if (jta.getText().contains(source)) {
						String result = jta.getText().replace(source, target);
						jta.setText(result);
					}
				}
			});
			p1.setLayout(new FlowLayout());
			p2.setLayout(new FlowLayout());
			p3.setLayout(new FlowLayout());
			p1.add(search);
			p1.add(jtf1);
			p2.add(replace);
			p2.add(jtf2);
			p3.add(confirm);
			this.getContentPane().add(p1);
			this.getContentPane().add(p2);
			this.getContentPane().add(p3);
			this.setLocationRelativeTo(null);
			this.setResizable(false);
			this.setDefaultCloseOperation(HIDE_ON_CLOSE);
			this.setVisible(true);
		}
	}

	// 主函數
	public static void main(String[] args) {
		new EditPlus();
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章