package notepade;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.Image;
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.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
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.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
public class Notepad extends JFrame implements ActionListener, DocumentListener {
private static final long serialVersionUID = 1L;
JMenu file, edit, mode, view, help;
// ---------------文件菜单
JMenuItem news, open, save, Asave, print, exit;
// ---------------编辑菜单
JMenuItem undos, cut, copy, paste, del, search, searchNext, replace,
turnto, selectAll, timeDate;
// ---------------格式菜单
JCheckBoxMenuItem LineWrap;
JMenu fontColor;
JMenuItem fonts, fgColor, bgColor;
// ---------------查看菜单
JCheckBoxMenuItem status;
// ---------------帮助菜单
JMenuItem topic, about;
// ---------------弹出菜单级菜单项
JPopupMenu jpm;
JMenuItem jmiu, jmic, jmico, jmip, jmid, jmisa;
// ---------------工具栏按钮
JButton newb, openb, saveb, Asaveb, printb, undob, redob, cutb, copyb,
pasteb, delb, searchb, timeb, fontb, boldb, italicb, fgcolorb,
bgcolorb, helpb;
// 文本编辑区域
static JTextArea Text;
// 状态栏标签
JLabel jl1, jl2, jl3;
JToolBar jtb;
// ---------------系统剪贴板
Toolkit tk = Toolkit.getDefaultToolkit();
Clipboard cb = tk.getSystemClipboard();
// ---------------创建撤消操作管理器
protected UndoManager undo = new UndoManager();
protected UndoableEditListener uel = new UndoHandler();
// ----------------其它变量
boolean isNewFile = true; // 是否新文件(未保存过的)
File currentFile; // 当前文件名
String oldValue; // 存放编辑区原来的内容,用于比较文本是否有改动
JButton fontOkButton; // 字体设置里的"确定"按钮
// ----------------设置编辑区默认字体
protected Font defaultFont = new Font("宋体", Font.PLAIN, 12);
GregorianCalendar time = new GregorianCalendar();
int hour = time.get(Calendar.HOUR_OF_DAY);
int min = time.get(Calendar.MINUTE);
int second = time.get(Calendar.SECOND);
File sfn, fn = null;
public Notepad() {
this.setTitle("无标题 - 记事本");
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
Container c = getContentPane();
// System.out.println(Text.getDragEnabled()); //支持自动拖放
JScrollPane jsp = new JScrollPane(Text);
jsp
.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
Text.setWrapStyleWord(true); // 设置单词在一行不足容纳时换行
Text.setLineWrap(true);
Text.setFont(defaultFont); // 设置编辑区默认字体
Text.setBackground(Color.white); // 设置编辑区默认背景色
Text.setForeground(Color.black); // 设置编辑区默认前景色
oldValue = Text.getText(); // 获取原文本编辑区的内容
// --------------------------编辑区注册事件监听
Text.getDocument().addUndoableEditListener(uel); // 添加负责通知任何更改的撤消侦听器
Text.getDocument().addDocumentListener(this); // 添加负责通知任何更改的文档侦听器
JMenuBar MenuBar = new JMenuBar();
file = new JMenu("文件(F)", true); // 创建菜单
edit = new JMenu("编辑(E)", true);
mode = new JMenu("格式(O)", true);
view = new JMenu("查看(V)", true);
help = new JMenu("帮助(H)", true);
edit.addActionListener(new ActionListener() // 注册事件监听
{
public void actionPerformed(ActionEvent e) {
checkMenuItemEnabled(); // 设置剪切、复制、粘贴、删除等功能的可用性
}
});
file.setMnemonic('F');
edit.setMnemonic('E');
mode.setMnemonic('O');
view.setMnemonic('V');
help.setMnemonic('H');
MenuBar.add(file);
MenuBar.add(edit);
MenuBar.add(mode);
MenuBar.add(view);
MenuBar.add(help);
// --------------文件菜单
news = new JMenuItem("新建(N)", 'N');
open = new JMenuItem("打开(O)", 'O');
save = new JMenuItem("保存(S)", 'S');
Asave = new JMenuItem("另存为(A)", 'A');
print = new JMenuItem("打印(P)", 'P');
exit = new JMenuItem("退出(X)", 'X');
news.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
InputEvent.CTRL_MASK));
open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
InputEvent.CTRL_MASK));
save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
InputEvent.CTRL_MASK));
print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
InputEvent.CTRL_MASK));
news.addActionListener(this); // 注册事件监听
open.addActionListener(this);
save.addActionListener(this);
Asave.addActionListener(this);
print.addActionListener(this);
exit.addActionListener(this);
file.add(news); // 添加菜单项
file.add(open);
file.add(save);
file.add(Asave);
file.addSeparator(); // 添加分割线
file.add(print);
file.addSeparator(); // 添加分割线
file.add(exit);
// --------------编辑菜单
undos = new JMenuItem("撤消(U)", 'U');
cut = new JMenuItem("剪切(T)", 'T');
copy = new JMenuItem("复制(C)", 'C');
paste = new JMenuItem("粘贴(P)", 'P');
del = new JMenuItem("删除(L)", 'L');
search = new JMenuItem("查找(F)", 'F');
searchNext = new JMenuItem("查找下一个(N)", 'N');
replace = new JMenuItem("替换(R)", 'R');
turnto = new JMenuItem("转到(G)", 'G');
selectAll = new JMenuItem("全选(A)", 'A');
timeDate = new JMenuItem("时间/日期(D)", 'D');
cut.setEnabled(false);
undos.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z,
InputEvent.CTRL_MASK));
cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
InputEvent.CTRL_MASK));
copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
InputEvent.CTRL_MASK));
paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
InputEvent.CTRL_MASK));
del.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
search.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,
InputEvent.CTRL_MASK));
searchNext.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0));
replace.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,
InputEvent.CTRL_MASK));
turnto.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G,
InputEvent.CTRL_MASK));
selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
InputEvent.CTRL_MASK));
timeDate.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
undos.addActionListener(this); // 注册事件监听
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
del.addActionListener(this);
search.addActionListener(this);
searchNext.addActionListener(this);
replace.addActionListener(this);
turnto.addActionListener(this);
selectAll.addActionListener(this);
timeDate.addActionListener(this);
edit.add(undos); // 添加菜单项
edit.addSeparator(); // 添加分割线
edit.add(cut);
edit.add(copy);
edit.add(paste);
edit.add(del);
edit.addSeparator();
edit.add(search);
edit.add(searchNext);
edit.add(replace);
edit.add(turnto);
edit.addSeparator();
edit.add(selectAll);
edit.add(timeDate);
// --------------格式菜单
LineWrap = new JCheckBoxMenuItem("自动换行(W)");
LineWrap.setMnemonic('W');
LineWrap.setState(true);
fonts = new JMenuItem("字体(F)", 'F');
fontColor = new JMenu("颜色");
fgColor = new JMenuItem("字体颜色");
bgColor = new JMenuItem("背景颜色");
LineWrap.addActionListener(this); // 注册事件监听
fonts.addActionListener(this);
fgColor.addActionListener(this);
bgColor.addActionListener(this);
mode.add(LineWrap); // 添加菜单项
mode.addSeparator();
mode.add(fonts);
mode.add(fontColor);
fontColor.add(fgColor);
fontColor.add(bgColor);
// --------------查看菜单
status = new JCheckBoxMenuItem("状态栏(S)");
status.setMnemonic('S');
status.setState(true);
status.addActionListener(this);
view.add(status);
// --------------帮助菜单
topic = new JMenuItem("帮助(H)", 'H');
about = new JMenuItem("关于(A)", 'A');
topic.addActionListener(this);
about.addActionListener(this);
help.add(topic);
help.addSeparator(); // 添加分割线
help.add(about);
// -------------------创建右键弹出菜单
jpm = new JPopupMenu();
jmiu = new JMenuItem("撤消(U)", 'U');
jmic = new JMenuItem("剪切(T)", 'T');
jmico = new JMenuItem("复制(C)", 'C');
jmip = new JMenuItem("粘贴(P)", 'P');
jmid = new JMenuItem("删除(D)", 'D');
jmisa = new JMenuItem("全选(A)", 'A');
jmiu.setEnabled(false); // 撤消选项初始设为不可用
// ---------------向右键菜单添加菜单项和分隔符
jpm.add(jmiu);
jpm.addSeparator();
jpm.add(jmic);
jpm.add(jmico);
jpm.add(jmip);
jpm.add(jmid);
jpm.addSeparator();
jpm.add(jmisa);
// --------------------右键菜单注册事件
jmiu.addActionListener(this);
jmic.addActionListener(this);
jmico.addActionListener(this);
jmip.addActionListener(this);
jmid.addActionListener(this);
jmisa.addActionListener(this);
// --------------------文本编辑区注册右键菜单事件
Text.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
checkForTriggerEvent(e);
}
public void mouseReleased(MouseEvent e) {
checkForTriggerEvent(e);
}
private void checkForTriggerEvent(MouseEvent e) {
if (e.isPopupTrigger())
jpm.show(e.getComponent(), e.getX(), e.getY());// 在组件调用者的坐标空间中的位置
// X、Y
// 显示弹出菜单。
else {
jl3.setText("当前光标所在行数: " + getlineNumber());
}
checkMenuItemEnabled(); // 设置剪切、复制、粘贴、删除等功能的可用性
Text.requestFocus(); // 编辑区获取焦点
}
});
// ----------------------------创建工具栏
JPanel toolBar = new JPanel();
toolBar.setLayout(new FlowLayout(FlowLayout.LEFT));
Icon newIcon = createImageIcon("Icons/new.gif");
Icon openIcon = createImageIcon("Icons/open.gif");
Icon saveIcon = createImageIcon("Icons/save.gif");
Icon saveAsIcon = createImageIcon("Icons/saveas.gif");
Icon printIcon = createImageIcon("Icons/print.gif");
Icon undoIcon = createImageIcon("Icons/undo.gif");
Icon cutIcon = createImageIcon("Icons/cut.gif");
Icon copyIcon = createImageIcon("Icons/copy.gif");
Icon pasteIcon = createImageIcon("Icons/paste.gif");
Icon deleteIcon = createImageIcon("Icons/delete.gif");
Icon searchIcon = createImageIcon("Icons/search.gif");
Icon timeIcon = createImageIcon("Icons/time.gif");
Icon fontIcon = createImageIcon("Icons/font.gif");
Icon boldIcon = createImageIcon("Icons/bold.gif");
Icon italicIcon = createImageIcon("Icons/italic.gif");
Icon bgcolorIcon = createImageIcon("Icons/bgcolor.gif");
Icon fgcolorIcon = createImageIcon("Icons/fgcolor.gif");
Icon helpIcon = createImageIcon("Icons/help.gif");
newb = new JButton(newIcon);
openb = new JButton(openIcon);
saveb = new JButton(saveIcon);
Asaveb = new JButton(saveAsIcon);
printb = new JButton(printIcon);
undob = new JButton(undoIcon);
undob.setEnabled(false);
cutb = new JButton(cutIcon);
cutb.setEnabled(false);
copyb = new JButton(copyIcon);
copyb.setEnabled(false);
pasteb = new JButton(pasteIcon);
pasteb.setEnabled(false);
delb = new JButton(deleteIcon);
delb.setEnabled(false);
searchb = new JButton(searchIcon);
timeb = new JButton(timeIcon);
fontb = new JButton(fontIcon);
boldb = new JButton(boldIcon);
italicb = new JButton(italicIcon);
fgcolorb = new JButton(fgcolorIcon);
bgcolorb = new JButton(bgcolorIcon);
helpb = new JButton(helpIcon);
newb.setPreferredSize(new Dimension(22, 22));
openb.setPreferredSize(new Dimension(22, 22));
saveb.setPreferredSize(new Dimension(22, 22));
Asaveb.setPreferredSize(new Dimension(22, 22));
printb.setPreferredSize(new Dimension(22, 22));
undob.setPreferredSize(new Dimension(22, 22));
cutb.setPreferredSize(new Dimension(22, 22));
copyb.setPreferredSize(new Dimension(22, 22));
pasteb.setPreferredSize(new Dimension(22, 22));
delb.setPreferredSize(new Dimension(22, 22));
searchb.setPreferredSize(new Dimension(22, 22));
timeb.setPreferredSize(new Dimension(22, 22));
fontb.setPreferredSize(new Dimension(22, 22));
boldb.setPreferredSize(new Dimension(22, 22));
italicb.setPreferredSize(new Dimension(22, 22));
fgcolorb.setPreferredSize(new Dimension(22, 22));
bgcolorb.setPreferredSize(new Dimension(22, 22));
helpb.setPreferredSize(new Dimension(22, 22));
// -----------------------------------注册工具栏按钮事件
newb.addActionListener(this);
openb.addActionListener(this);
saveb.addActionListener(this);
Asaveb.addActionListener(this);
printb.addActionListener(this);
undob.addActionListener(this);
cutb.addActionListener(this);
copyb.addActionListener(this);
pasteb.addActionListener(this);
delb.addActionListener(this);
searchb.addActionListener(this);
timeb.addActionListener(this);
fontb.addActionListener(this);
boldb.addActionListener(this);
italicb.addActionListener(this);
fgcolorb.addActionListener(this);
bgcolorb.addActionListener(this);
helpb.addActionListener(this);
// ------------------------设置按钮提示文字
newb.setToolTipText("新建");
openb.setToolTipText("打开");
saveb.setToolTipText("保存");
Asaveb.setToolTipText("另存为");
printb.setToolTipText("打印");
undob.setToolTipText("撤消");
cutb.setToolTipText("剪切");
copyb.setToolTipText("复制");
pasteb.setToolTipText("粘贴");
delb.setToolTipText("删除所选");
searchb.setToolTipText("查找与替换");
timeb.setToolTipText("插入时间/日期");
fontb.setToolTipText("设置字体");
boldb.setToolTipText("粗体");
italicb.setToolTipText("斜体");
fgcolorb.setToolTipText("设置字体颜色");
bgcolorb.setToolTipText("设置背景颜色");
helpb.setToolTipText("帮助");
// 设置撤消、重做、剪切、复制、粘贴、删除等工具栏按钮不可用时的图片(灰色)
undob.setDisabledIcon(createImageIcon("Icons/undo1.gif"));
cutb.setDisabledIcon(createImageIcon("Icons/cut1.gif"));
copyb.setDisabledIcon(createImageIcon("Icons/copy1.gif"));
pasteb.setDisabledIcon(createImageIcon("Icons/paste1.gif"));
delb.setDisabledIcon(createImageIcon("Icons/delete1.gif"));
// ------------------------向工具栏添加按钮
toolBar.add(newb);
toolBar.add(openb);
toolBar.add(saveb);
toolBar.add(Asaveb);
toolBar.add(printb);
toolBar.add(undob);
toolBar.add(cutb);
toolBar.add(copyb);
toolBar.add(pasteb);
toolBar.add(delb);
toolBar.add(searchb);
toolBar.add(timeb);
toolBar.add(fontb);
toolBar.add(boldb);
toolBar.add(italicb);
toolBar.add(fgcolorb);
toolBar.add(bgcolorb);
toolBar.add(helpb);
// --------------------------------------向容器添加工具栏
c.add(toolBar, BorderLayout.NORTH);
// -----------------------------------创建和添加状态栏
jtb = new JToolBar();
jtb.setLayout(new FlowLayout(FlowLayout.LEFT));
jl1 = new JLabel("按F1获取帮助 ");
jl2 = new JLabel(" 当前时间:" + hour + ":" + min + ":" + second);
jl3 = new JLabel(" 当前光标所在行数" + getlineNumber());
jtb.add(jl1);
jtb.addSeparator();
jtb.add(jl2);
jtb.addSeparator();
jtb.add(jl3);
c.add(jtb, BorderLayout.SOUTH);
jtb.setVisible(true);
// ------------------------------------改变标题栏窗口左侧默认图标
Toolkit tk = Toolkit.getDefaultToolkit();
Image image = tk.createImage("Icons/notepad.gif");
this.setIconImage(image);
this.setJMenuBar(MenuBar); // 向窗口添加菜单条
c.add(jsp, BorderLayout.CENTER); // 向容器添加文本编辑区
this.pack();
this.setSize(800, 800);
this.setVisible(true);
checkMenuItemEnabled();
Text.requestFocus();
// this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
checkText();
}
});
Clock clock = new Clock();
clock.start();
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Notepad.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public void checkText() {
Text.requestFocus();
String cv = Text.getText();
boolean isTextChange = (cv.equals(oldValue)) ? false : true;
if (isTextChange) {
int saveChoose = JOptionPane.showConfirmDialog(this,
"您的文件尚未保存。是否保存?", "提示", JOptionPane.YES_NO_CANCEL_OPTION);
if (saveChoose == JOptionPane.YES_OPTION) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setApproveButtonText("确定");
fileChooser.setDialogTitle("另存为");
int result = fileChooser.showSaveDialog(this);
if (result == JFileChooser.CANCEL_OPTION) {
jl1.setText("您没有选择任何文件");
return;
}
sfn = fileChooser.getSelectedFile();
if (sfn == null || sfn.getName().equals(""))
JOptionPane.showMessageDialog(this, "不合法的文件名", "不合法的文件名",
JOptionPane.ERROR_MESSAGE);
else {
saveFile();
Text.setText("");
this.setTitle("新建文本");
jl1.setText(" 新建文本");
}
} else if (saveChoose == JOptionPane.NO_OPTION) {
System.exit(0);
} else if (saveChoose == JOptionPane.CANCEL_OPTION) {
Text.requestFocus();
}
} else if (!isTextChange) {
System.exit(0);
}
}
public void checkMenuItemEnabled() {
String selectText = Text.getSelectedText();
if (selectText == null) {
cut.setEnabled(false);
jmic.setEnabled(false);
cutb.setEnabled(false);
copy.setEnabled(false);
jmico.setEnabled(false);
copyb.setEnabled(false);
del.setEnabled(false);
jmid.setEnabled(false);
delb.setEnabled(false);
} else {
cut.setEnabled(true);
jmic.setEnabled(true);
cutb.setEnabled(true);
copy.setEnabled(true);
jmico.setEnabled(true);
copyb.setEnabled(true);
del.setEnabled(true);
jmid.setEnabled(true);
delb.setEnabled(true);
}
// 粘贴功能可用性判断
Transferable contents = cb.getContents(this);
if (contents == null) {
paste.setEnabled(false);
jmip.setEnabled(false);
pasteb.setEnabled(false);
} else {
paste.setEnabled(true);
jmip.setEnabled(true);
pasteb.setEnabled(true);
}
}
public int getlineNumber() {
int totalLine = Text.getLineCount();
int[] lineNumber = new int[totalLine + 1];
int pos = 0, t = 0, num = 0, i = 0;
String s = Text.getText();
while (true) {
pos = s.indexOf('/12', pos); // 返回 /n 所在的位置
if (pos == -1)
break;
lineNumber[t++] = pos++;
}
if (Text.getCaretPosition() <= lineNumber[0])
num = 1;
else {
if (Text.getCaretPosition() > lineNumber[Text.getLineCount() - 1])
num = Text.getLineCount();
for (i = 0; i < totalLine + 1; i++) {
if (Text.getCaretPosition() <= lineNumber[i]) {
num = i + 1;
break;
} else
continue;
}
}
return num;
}
public void saveFile() {
try {
FileWriter fw = new FileWriter(sfn);
fw.write(Text.getText());
fw.close();
} catch (Exception e) {
}
}
public void mySearch() {
final JDialog findDialog = new JDialog(this, "查找与替换", true);
Container con = findDialog.getContentPane();
con.setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel searchContentLabel = new JLabel("查找内容(N) :");
JLabel replaceContentLabel = new JLabel("替换为(P) :");
final JTextField findText = new JTextField(22);
final JTextField replaceText = new JTextField(22);
final JCheckBox matchcase = new JCheckBox("区分大小写");
ButtonGroup bGroup = new ButtonGroup();
final JRadioButton up = new JRadioButton("向上(U)");
final JRadioButton down = new JRadioButton("向下(D)");
down.setSelected(true);
bGroup.add(up);
bGroup.add(down);
JButton searchNext = new JButton("查找下一个(F)");
JButton replace = new JButton("替换(R)");
final JButton replaceAll = new JButton("全部替换(A)");
searchNext.setPreferredSize(new Dimension(110, 22));
replace.setPreferredSize(new Dimension(110, 22));
replaceAll.setPreferredSize(new Dimension(110, 22));
// "替换"按钮的事件处理
replace.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (replaceText.getText().length() == 0
&& Text.getSelectedText() != null)
Text.replaceSelection("");
if (replaceText.getText().length() > 0
&& Text.getSelectedText() != null)
Text.replaceSelection(replaceText.getText());
}
});
// "替换全部"按钮的事件处理
replaceAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Text.setCaretPosition(0); // 将光标放到编辑区开头
int a = 0, b = 0, replaceCount = 0;
if (findText.getText().length() == 0) {
JOptionPane.showMessageDialog(findDialog, "请填写查找内容!", "提示",
JOptionPane.WARNING_MESSAGE);
findText.requestFocus(true);
return;
}
while (a > -1) {
int FindStartPos = Text.getCaretPosition();
String str1, str2, str3, str4, strA, strB;
str1 = Text.getText();
str2 = str1.toLowerCase();
str3 = findText.getText();
str4 = str3.toLowerCase();
if (matchcase.isSelected()) {
strA = str1;
strB = str3;
} else {
strA = str2;
strB = str4;
}
if (up.isSelected()) {
if (Text.getSelectedText() == null) {
a = strA.lastIndexOf(strB, FindStartPos - 1);
} else {
a = strA.lastIndexOf(strB, FindStartPos
- findText.getText().length() - 1);
}
} else if (down.isSelected()) {
if (Text.getSelectedText() == null) {
a = strA.indexOf(strB, FindStartPos);
} else {
a = strA.indexOf(strB, FindStartPos
- findText.getText().length() + 1);
}
}
if (a > -1) {
if (up.isSelected()) {
Text.setCaretPosition(a);
b = findText.getText().length();
Text.select(a, a + b);
} else if (down.isSelected()) {
Text.setCaretPosition(a);
b = findText.getText().length();
Text.select(a, a + b);
}
} else {
if (replaceCount == 0) {
JOptionPane.showMessageDialog(findDialog,
"找不到您查找的内容!", "记事本",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(findDialog, "成功替换"
+ replaceCount + "个匹配内容!", "替换成功",
JOptionPane.INFORMATION_MESSAGE);
}
}
if (replaceText.getText().length() == 0
&& Text.getSelectedText() != null) {
Text.replaceSelection("");
replaceCount++;
}
if (replaceText.getText().length() > 0
&& Text.getSelectedText() != null) {
Text.replaceSelection(replaceText.getText());
replaceCount++;
}
}// end while
}
}); /* "替换全部"按钮的事件处理结束 */
// "查找下一个"按钮事件处理
searchNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int a = 0, b = 0;
int FindStartPos = Text.getCaretPosition();
String str1, str2, str3, str4, strA, strB;
str1 = Text.getText();
str2 = str1.toLowerCase();
str3 = findText.getText();
str4 = str3.toLowerCase();
// "区分大小写"的CheckBox被选中
if (matchcase.isSelected()) {
strA = str1;
strB = str3;
} else {
strA = str2;
strB = str4;
}
if (up.isSelected()) {
if (Text.getSelectedText() == null) {
a = strA.lastIndexOf(strB, FindStartPos - 1);
} else {
a = strA.lastIndexOf(strB, FindStartPos
- findText.getText().length() - 1);
}
} else if (down.isSelected()) {
if (Text.getSelectedText() == null) {
a = strA.indexOf(strB, FindStartPos);
} else {
a = strA.indexOf(strB, FindStartPos
- findText.getText().length() + 1);
}
}
if (a > -1) {
if (up.isSelected()) {
Text.setCaretPosition(a);
b = findText.getText().length();
Text.select(a, a + b);
} else if (down.isSelected()) {
Text.setCaretPosition(a);
b = findText.getText().length();
Text.select(a, a + b);
}
} else {
JOptionPane.showMessageDialog(null, "找不到您查找的内容!", "记事本",
JOptionPane.INFORMATION_MESSAGE);
}
}
});/* "查找下一个"按钮事件处理结束 */
// "取消"按钮及事件处理
JButton cancel = new JButton("取消");
cancel.setPreferredSize(new Dimension(110, 22));
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
findDialog.dispose();
}
});
// 创建"查找与替换"对话框的界面
JPanel bottomPanel = new JPanel();
JPanel centerPanel = new JPanel();
JPanel topPanel = new JPanel();
JPanel direction = new JPanel();
direction.setBorder(BorderFactory.createTitledBorder("方向 "));
direction.add(up);
direction.add(down);
direction.setPreferredSize(new Dimension(170, 60));
JPanel replacePanel = new JPanel();
replacePanel.setLayout(new GridLayout(2, 1));
replacePanel.add(replace);
replacePanel.add(replaceAll);
topPanel.add(searchContentLabel);
topPanel.add(findText);
topPanel.add(searchNext);
centerPanel.add(replaceContentLabel);
centerPanel.add(replaceText);
centerPanel.add(replacePanel);
bottomPanel.add(matchcase);
bottomPanel.add(direction);
bottomPanel.add(cancel);
con.add(topPanel);
con.add(centerPanel);
con.add(bottomPanel);
// 设置"查找与替换"对话框的大小、可更改大小(否)、位置和可见性
findDialog.setSize(410, 210);
findDialog.setResizable(false);
findDialog.setLocation(230, 280);
findDialog.setVisible(true);
}
/* 方法mySearch()结束 */
public void removeUpdate(DocumentEvent e) {
undos.setEnabled(true);
jmiu.setEnabled(true);
undob.setEnabled(true);
}
public void insertUpdate(DocumentEvent e) {
undos.setEnabled(true);
jmiu.setEnabled(true);
undob.setEnabled(true);
}
public void changedUpdate(DocumentEvent e) {
undos.setEnabled(true);
jmiu.setEnabled(true);
undob.setEnabled(true);
}
// End of DocumentListener
// 实现ActionListener的事件处理方法public void actionPerformed(ActionEvent e)
public void actionPerformed(ActionEvent e) {
// 新建
if (e.getActionCommand().equals("新建(N)") || e.getSource() == newb)
// 最初发生 Event 的对象
// if(e.getSource()==mFile_New||e.getSource()==newButton)
{
Text.requestFocus();
String cv = Text.getText();
boolean isTextChange = (cv.equals(oldValue)) ? false : true;
if (isTextChange) {
int saveChoose = JOptionPane.showConfirmDialog(this,
"您的文件尚未保存。是否保存?", "提示",
JOptionPane.YES_NO_CANCEL_OPTION);
if (saveChoose == JOptionPane.YES_OPTION) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setApproveButtonText("确定");
fileChooser.setDialogTitle("另存为");
int result = fileChooser.showSaveDialog(this);
if (result == JFileChooser.CANCEL_OPTION) {
jl1.setText("您没有选择任何文件");
return;
}
sfn = fileChooser.getSelectedFile();
if (sfn == null || sfn.getName().equals(""))
JOptionPane.showMessageDialog(this, "不合法的文件名",
"不合法的文件名", JOptionPane.ERROR_MESSAGE);
else {
saveFile();
Text.setText("");
this.setTitle("新建文本");
jl1.setText(" 新建文本");
}
} else if (saveChoose == JOptionPane.NO_OPTION) {
Text.replaceRange("", 0, Text.getText().length());
jl1.setText(" 新建文件");
this.setTitle("无标题 - 记事本");
isNewFile = true;
undo.discardAllEdits(); // 撤消所有的"撤消"操作
undos.setEnabled(false);
jmiu.setEnabled(false);
undob.setEnabled(false);
redob.setEnabled(false);
oldValue = Text.getText();
} else if (saveChoose == JOptionPane.CANCEL_OPTION) {
return;
}
} else {
// Text.replaceRange("", 0, Text.getText().length());
Text.setText("");
jl1.setText(" 新建文件");
this.setTitle("无标题 - 记事本");
isNewFile = true;
undo.discardAllEdits();
undos.setEnabled(false);
jmiu.setEnabled(false);
undob.setEnabled(false);
oldValue = Text.getText();
}
}// 新建处理结束
// 打开
else if (e.getActionCommand().equals("打开(O)") || e.getSource() == openb) {
Text.requestFocus();
String cv = Text.getText();
boolean isTextChange = (cv.equals(oldValue)) ? false : true;
if (isTextChange) {
int saveChoose = JOptionPane.showConfirmDialog(this,
"您的文件尚未保存。是否保存?", "提示",
JOptionPane.YES_NO_CANCEL_OPTION);
if (saveChoose == JOptionPane.YES_OPTION) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setApproveButtonText("确定");
fileChooser.setDialogTitle("另存为");
int result = fileChooser.showSaveDialog(this);
if (result == JFileChooser.CANCEL_OPTION) {
jl1.setText("您没有选择任何文件");
return;
}
sfn = fileChooser.getSelectedFile();
if (sfn == null || sfn.getName().equals(""))
JOptionPane.showMessageDialog(this, "不合法的文件名",
"不合法的文件名", JOptionPane.ERROR_MESSAGE);
else {
saveFile();
isNewFile = false;
currentFile = sfn;
oldValue = Text.getText();
this.setTitle(sfn.getName() + " - 记事本");
jl1.setText(" 当前打开文件:" + sfn.getAbsoluteFile());
}
} else if (saveChoose == JOptionPane.NO_OPTION) {
String str = null;
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setApproveButtonText("确定");
fileChooser.setDialogTitle("打开文件");
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.CANCEL_OPTION) {
jl1.setText("您没有选择任何文件");
return;
}
fn = fileChooser.getSelectedFile();
if (fn == null || fn.getName().equals(""))
JOptionPane.showMessageDialog(this, "不合法的文件名",
"不合法的文件名", JOptionPane.ERROR_MESSAGE);
else {
try {
FileReader fr = new FileReader(fn);
BufferedReader bfr = new BufferedReader(fr);
Text.setText("");
while ((str = bfr.readLine()) != null) {// 每次读取一行,直到文件结束
Text.append(str + "/15/12");
}// endwhile
this.setTitle(fn.getName() + " - 记事本");
jl1.setText(" 当前打开文件:" + fn.getAbsoluteFile());
fr.close();
isNewFile = false;
currentFile = fn;
oldValue = Text.getText();
} catch (IOException ioException) {
}
}
} else {
return;
}
}
else {
String str = null;
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setApproveButtonText("确定");
fileChooser.setDialogTitle("打开文件");
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.CANCEL_OPTION) {
jl1.setText(" 您没有选择任何文件");
return;
}
fn = fileChooser.getSelectedFile();
if (fn == null || fn.getName().equals(""))
JOptionPane.showMessageDialog(this, "不合法的文件名", "不合法的文件名",
JOptionPane.ERROR_MESSAGE);
else {
try {
FileReader fr = new FileReader(fn);
BufferedReader bfr = new BufferedReader(fr);
Text.setText("");
while ((str = bfr.readLine()) != null) {// 每次读取一行,直到文件结束
Text.append(str + "/15/12");
}// endwhile
this.setTitle(fn.getName() + " - 记事本");
jl1.setText(" 当前打开文件:" + fn.getAbsoluteFile());
fr.close();
isNewFile = false;
currentFile = fn;
oldValue = Text.getText();
} catch (IOException ioException) {
}
}
}
}// "打开"处理结束
// 保存
else if (e.getSource() == save || e.getSource() == saveb) {
Text.requestFocus();
if (isNewFile) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setApproveButtonText("确定");
fileChooser.setDialogTitle("另存为");
int result = fileChooser.showSaveDialog(this);
if (result == JFileChooser.CANCEL_OPTION) {
jl1.setText(" 您没有选择任何文件");
return;
}
sfn = fileChooser.getSelectedFile();
if (sfn == null || sfn.getName().equals(""))
JOptionPane.showMessageDialog(this, "不合法的文件名", "不合法的文件名",
JOptionPane.ERROR_MESSAGE);
else {
saveFile();
isNewFile = false;
currentFile = sfn;
oldValue = Text.getText();
this.setTitle(sfn.getName() + " - 记事本");
jl1.setText(" 当前打开文件:" + sfn.getAbsoluteFile());
}
} else {
try {
FileWriter fw = new FileWriter(currentFile);
BufferedWriter bfw = new BufferedWriter(fw);
bfw.write(Text.getText(), 0, Text.getText().length());
bfw.flush();
fw.close();
} catch (IOException ioException) {
}
}
}// "保存"处理结束
// 另存为
else if (e.getSource() == Asave || e.getSource() == Asaveb) {
Text.requestFocus();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setApproveButtonText("确定");
fileChooser.setDialogTitle("另存为");
int result = fileChooser.showSaveDialog(this);
if (result == JFileChooser.CANCEL_OPTION) {
jl1.setText(" 您没有选择任何文件");
return;
}
sfn = fileChooser.getSelectedFile();
if (sfn == null || sfn.getName().equals(""))
JOptionPane.showMessageDialog(this, "不合法的文件名", "不合法的文件名",
JOptionPane.ERROR_MESSAGE);
else {
saveFile();
isNewFile = false;
currentFile = sfn;
oldValue = Text.getText();
this.setTitle(sfn.getName() + " - 记事本");
jl1.setText(" 当前打开文件:" + sfn.getAbsoluteFile());
}
}// "另存为"处理结束
// 打印
else if (e.getSource() == print || e.getSource() == printb) {
Text.requestFocus();
JOptionPane.showMessageDialog(this, "此功能尚未添加!", "提示",
JOptionPane.WARNING_MESSAGE);
}
// 退出
else if (e.getSource() == exit) {
int exitChoose = JOptionPane.showConfirmDialog(this, "确定要退出么?",
"退出提示", JOptionPane.OK_CANCEL_OPTION);
if (exitChoose == JOptionPane.OK_OPTION) {
checkText();
} else {
return;
}
}
// 撤消
else if (e.getSource() == undos || e.getSource() == jmiu
|| e.getSource() == undob) {
Text.requestFocus();
if (undo.canUndo()) {
try {
undo.undo();
} catch (CannotUndoException ex) {
System.out.println("Unable to undo: " + ex);
ex.printStackTrace();
}
if (!undo.canUndo()) {
undos.setEnabled(false);
jmiu.setEnabled(false);
undob.setEnabled(false);
}
}
}
// 剪切
else if (e.getSource() == cut || e.getSource() == jmic
|| e.getSource() == cutb) {
Text.requestFocus();
String text = Text.getSelectedText();
StringSelection selection = new StringSelection(text);
cb.setContents(selection, null);
Text.replaceRange("", Text.getSelectionStart(), Text
.getSelectionEnd());
checkMenuItemEnabled(); // 设置剪切、复制、粘贴、删除等功能的可用性
}
// 复制
else if (e.getSource() == copy || e.getSource() == jmico
|| e.getSource() == copyb) {
Text.requestFocus();
String text = Text.getSelectedText();
StringSelection selection = new StringSelection(text);
cb.setContents(selection, null);
checkMenuItemEnabled(); // 设置剪切、复制、粘贴、删除等功能的可用性
}
// 粘贴
else if (e.getSource() == paste || e.getSource() == jmip
|| e.getSource() == pasteb) {
Text.requestFocus();
Transferable contents = cb.getContents(this);
if (contents == null)
return;
String text;
text = "";
try {
text = (String) contents
.getTransferData(DataFlavor.stringFlavor);
} catch (Exception exception) {
}
Text.replaceRange(text, Text.getSelectionStart(), Text
.getSelectionEnd());
checkMenuItemEnabled(); // 设置剪切、复制、粘贴、删除等功能的可用性
}
// 删除
else if (e.getSource() == del || e.getSource() == jmid
|| e.getSource() == delb) {
Text.requestFocus();
Text.replaceRange("", Text.getSelectionStart(), Text
.getSelectionEnd());
checkMenuItemEnabled(); // 设置剪切、复制、粘贴、删除等功能的可用性
}
// 查找
else if (e.getSource() == search || e.getSource() == searchb) {
Text.requestFocus();
if (e.getSource() == searchb) {
Text.requestFocus();
Text.setCaretPosition(0);
}
mySearch();
}
// 查找下一个(此功能尚未能很好实现,所以就先用查找功能来代替)
else if (e.getSource() == searchNext) {
mySearch();
}
// 替换(与查找功能集成在一起了)
else if (e.getSource() == replace) {
mySearch();
}
// 转到
else if (e.getSource() == turnto) {
final JDialog gotoDialog = new JDialog(this, "转到下列行");
JLabel gotoLabel = new JLabel("行数(L):");
final JTextField linenum = new JTextField(5);
linenum.setText("1");
linenum.selectAll();
JButton okButton = new JButton("确定");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int totalLine = Text.getLineCount();
int[] lineNumber = new int[totalLine + 1];
String s = Text.getText();
int pos = 0, t = 0;
while (true) {
pos = s.indexOf('/12', pos);
// System.out.println("引索pos:"+pos);
if (pos == -1)
break;
lineNumber[t++] = pos++;
}
int gt = 1;
try {
gt = Integer.parseInt(linenum.getText());
} catch (NumberFormatException efe) {
JOptionPane.showMessageDialog(null, "请输入行数!", "提示",
JOptionPane.WARNING_MESSAGE);
linenum.requestFocus(true);
return;
}
if (gt < 2 || gt >= totalLine) {
if (gt < 2)
Text.setCaretPosition(0);
else
Text.setCaretPosition(s.length());
} else
Text.setCaretPosition(lineNumber[gt - 2] + 1);
gotoDialog.dispose();
}
});
JButton cancelButton = new JButton("取消");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gotoDialog.dispose();
}
});
Container con = gotoDialog.getContentPane();
con.setLayout(new FlowLayout());
con.add(gotoLabel);
con.add(linenum);
con.add(okButton);
con.add(cancelButton);
gotoDialog.setSize(200, 100);
gotoDialog.setResizable(false);
gotoDialog.setLocation(300, 280);
gotoDialog.setVisible(true);
}// "转到"处理结束
// 插入时间日期
else if (e.getSource() == timeDate || e.getSource() == timeb) {
Text.requestFocus();
SimpleDateFormat currentDateTime = new SimpleDateFormat(
"HH:mm yyyy-MM-dd");
Text.insert(currentDateTime.format(new Date()), Text
.getCaretPosition());
}
// 全选
else if (e.getSource() == jmisa || e.getSource() == selectAll) {
Text.selectAll();
}
// 自动换行
else if (e.getSource() == LineWrap) {
if (LineWrap.getState()) {
Text.setLineWrap(true);
} else
Text.setLineWrap(false);
}
// 字体设置
else if (e.getSource() == fonts || e.getSource() == fontb) {
Text.requestFocus();
new MyFont();
}
// 设置字体颜色(前景色)
else if (e.getSource() == fgColor || e.getSource() == fgcolorb) {
Text.requestFocus();
Color color = JColorChooser.showDialog(this, "更改字体颜色", Color.black);
if (color != null) {
Text.setForeground(color);
} else
return;
}
// 设置编辑区背景颜色
else if (e.getSource() == bgColor || e.getSource() == bgcolorb) {
Text.requestFocus();
Color color = JColorChooser.showDialog(this, "更改背景颜色", Color.white);
if (color != null) {
Text.setBackground(color);
} else
return;
}
// 设置状态栏可见性
else if (e.getSource() == status) {
if (status.getState())
jtb.setVisible(true);
else
jtb.setVisible(false);
}
// 帮助主题
else if (e.getSource() == topic || e.getSource() == helpb) {
JOptionPane.showMessageDialog(this, "记事本支持拖入文本读取/n"
+ "由于对编码不熟悉保存文/n件时未进行编码转换/n", "帮助主题",
JOptionPane.INFORMATION_MESSAGE);
}
// 关于
else if (e.getSource() == about) {
JOptionPane.showMessageDialog(this, " VXBB的记事本/n"
+ " QQ:491697374/n" + " JAVA图形界面练习/n", "关于记事本",
JOptionPane.INFORMATION_MESSAGE);
}
// 工具栏"粗体"按钮事件处理
else if (e.getSource() == boldb) {
Text.requestFocus();
Font tempFont = Text.getFont();
if (Text.getFont().getStyle() == Font.PLAIN) {
tempFont = new Font(Text.getFont().getFontName(), Font.BOLD,
Text.getFont().getSize());
} else if (Text.getFont().getStyle() == Font.ITALIC) {
tempFont = new Font(Text.getFont().getFontName(), Font.BOLD
+ Font.ITALIC, Text.getFont().getSize());
} else if (Text.getFont().getStyle() == Font.BOLD) {
tempFont = new Font(Text.getFont().getFontName(), Font.PLAIN,
Text.getFont().getSize());
} else if (Text.getFont().getStyle() == (Font.BOLD + Font.ITALIC)) {
tempFont = new Font(Text.getFont().getFontName(), Font.ITALIC,
Text.getFont().getSize());
}
Text.setFont(tempFont);
}
// 工具栏"斜体"按钮事件处理
else if (e.getSource() == italicb) {
Text.requestFocus();
Font tempFont = Text.getFont();
if (Text.getFont().getStyle() == Font.PLAIN) {
tempFont = new Font(Text.getFont().getFontName(), Font.ITALIC,
Text.getFont().getSize());
} else if (Text.getFont().getStyle() == Font.ITALIC) {
tempFont = new Font(Text.getFont().getFontName(), Font.PLAIN,
Text.getFont().getSize());
} else if (Text.getFont().getStyle() == Font.BOLD) {
tempFont = new Font(Text.getFont().getFontName(), Font.BOLD
+ Font.ITALIC, Text.getFont().getSize());
} else if (Text.getFont().getStyle() == (Font.BOLD + Font.ITALIC)) {
tempFont = new Font(Text.getFont().getFontName(), Font.BOLD,
Text.getFont().getSize());
}
Text.setFont(tempFont);
}
}/* 方法actionPerformed()结束 */
class Clock extends Thread { // 模拟时钟
public void run() {
while (true) {
GregorianCalendar time = new GregorianCalendar();
int hour = time.get(Calendar.HOUR_OF_DAY);
int min = time.get(Calendar.MINUTE);
int second = time.get(Calendar.SECOND);
jl2.setText(" 当前时间:" + hour + ":" + min + ":" + second);
try {
Thread.sleep(950);
} catch (InterruptedException exception) {
}
}
}
}
// 用于设置字体的类MyFont
class MyFont implements ActionListener {
final JDialog fontDialog;
final JTextField tfFont, tfSize, tfStyle;
final int fontStyleConst[] = { Font.PLAIN, Font.BOLD, Font.ITALIC,
Font.BOLD + Font.ITALIC };
final JList listStyle, listFont, listSize;
JLabel sample;
JPanel pane1, pane2, pane3, pane4;
// 构造函数MyFont
public MyFont() {
fontDialog = new JDialog(Notepad.this, "字体设置", true);
Container con = fontDialog.getContentPane();
con.setLayout(new BoxLayout(con, BoxLayout.Y_AXIS));
pane1 = new JPanel();
pane2 = new JPanel();
pane3 = new JPanel();
pane4 = new JPanel();
Font currentFont = Text.getFont();
JLabel lblFont = new JLabel("字体(F):");
JLabel lblStyle = new JLabel("字形(Y):");
JLabel lblSize = new JLabel("大小(S):");
lblStyle.setHorizontalAlignment(SwingConstants.CENTER);
lblSize.setHorizontalAlignment(SwingConstants.CENTER);
lblFont.setPreferredSize(new Dimension(91, 20));
lblStyle.setPreferredSize(new Dimension(82, 20));
lblSize.setPreferredSize(new Dimension(100, 20));
tfFont = new JTextField(13);
tfFont.setText(currentFont.getFontName());
tfFont.selectAll();
tfFont.setPreferredSize(new Dimension(200, 20));
tfStyle = new JTextField(10);
if (currentFont.getStyle() == Font.PLAIN)
tfStyle.setText("常规");
else if (currentFont.getStyle() == Font.BOLD)
tfStyle.setText("粗体");
else if (currentFont.getStyle() == Font.ITALIC)
tfStyle.setText("斜体");
else if (currentFont.getStyle() == (Font.BOLD + Font.ITALIC))
tfStyle.setText("粗斜体");
tfFont.selectAll();
tfStyle.setPreferredSize(new Dimension(200, 20));
tfSize = new JTextField(7);
tfSize.setText(currentFont.getSize() + "");
tfSize.selectAll();
tfSize.setPreferredSize(new Dimension(200, 20));
final String fontStyle[] = { "常规", "粗体", "斜体", "粗斜体" };
listStyle = new JList(fontStyle);
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
final String fontName[] = ge.getAvailableFontFamilyNames();
int defaultFontIndex = 0;
for (int i = 0; i < fontName.length; i++) {
if (fontName[i].equals(currentFont.getFontName())) {
defaultFontIndex = i;
break;
}
}
listFont = new JList(fontName);
listFont.setSelectedIndex(defaultFontIndex);
listFont.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listFont.setVisibleRowCount(7);
listFont.setFixedCellWidth(99);
listFont.setFixedCellHeight(20);
listFont.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
tfFont.setText(fontName[listFont.getSelectedIndex()]);
tfFont.requestFocus();
tfFont.selectAll();
updateSample();
}
});
listStyle.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (currentFont.getStyle() == Font.PLAIN)
listStyle.setSelectedIndex(0);
else if (currentFont.getStyle() == Font.BOLD)
listStyle.setSelectedIndex(1);
else if (currentFont.getStyle() == Font.ITALIC)
listStyle.setSelectedIndex(2);
else if (currentFont.getStyle() == (Font.BOLD + Font.ITALIC))
listStyle.setSelectedIndex(3);
listStyle.setVisibleRowCount(7);
listStyle.setFixedCellWidth(85);
listStyle.setFixedCellHeight(20);
listStyle.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
tfStyle.setText(fontStyle[listStyle.getSelectedIndex()]);
tfStyle.requestFocus();
tfStyle.selectAll();
updateSample();
}
});
final String fontSize[] = { "8", "9", "10", "11", "12", "14", "16",
"18", "20", "22", "24", "26", "28", "36", "48", "72" };
listSize = new JList(fontSize);
int defaultFontSizeIndex = 0;
for (int i = 0; i < fontSize.length; i++) {
if (fontSize[i].equals(currentFont.getSize() + "")) {
defaultFontSizeIndex = i;
break;
}
}
listSize.setSelectedIndex(defaultFontSizeIndex);
listSize.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listSize.setVisibleRowCount(7);
listSize.setFixedCellWidth(50);
listSize.setFixedCellHeight(20);
listSize.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
tfSize.setText(fontSize[listSize.getSelectedIndex()]);
tfSize.requestFocus();
tfSize.selectAll();
updateSample();
}
});
fontOkButton = new JButton("确定");
fontOkButton.addActionListener(this);
JButton cancelButton = new JButton("取消");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fontDialog.dispose();
}
});
sample = new JLabel(" 记事本 ");
sample.setHorizontalAlignment(SwingConstants.CENTER);
sample.setPreferredSize(new Dimension(150, 31));
JPanel samplePanel = new JPanel();
samplePanel.setBorder(BorderFactory.createTitledBorder("示例"));
samplePanel.add(sample);
pane1.add(lblFont);
pane1.add(lblStyle);
pane1.add(lblSize);
pane2.add(tfFont);
pane2.add(tfStyle);
pane2.add(tfSize);
pane3.add(new JScrollPane(listFont));
pane3.add(new JScrollPane(listStyle));
pane3.add(new JScrollPane(listSize));
pane4.add(samplePanel);
pane4.add(fontOkButton);
pane4.add(cancelButton);
con.add(pane1);
con.add(pane2);
con.add(pane3);
con.add(pane4);
updateSample();
fontDialog.pack();
fontDialog.setSize(400, 400);
fontDialog.setLocation(200, 200);
fontDialog.setResizable(false);
fontDialog.setVisible(true);
}// 构造函数结束
// 更新示例显示的字体和风格大小等
public void updateSample() {
Font sampleFont = new Font(tfFont.getText(),
fontStyleConst[listStyle.getSelectedIndex()], Integer
.parseInt(tfSize.getText()));
sample.setFont(sampleFont);
}// End method updateSample
// 设置文本编辑区的字体
public void actionPerformed(ActionEvent e) {
if (e.getSource() == fontOkButton) {
Font tempFont = new Font(tfFont.getText(),
fontStyleConst[listStyle.getSelectedIndex()], Integer
.parseInt(tfSize.getText()));
Text.setFont(tempFont);
fontDialog.dispose();
}
}// End method actionPerformed
}/* End of class MyFont */
// 实现了接口UndoableListener的类uel
class UndoHandler implements UndoableEditListener {
public void undoableEditHappened(UndoableEditEvent uee) {
undo.addEdit(uee.getEdit());
}
}
public static void main(String s[]) throws Exception{
// UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Text = new JTextArea();
Text.setDragEnabled(true); // 支持自动拖放
Text.setTransferHandler(new FileTransferHandler(Text));
new Notepad();
}
}
class FileTransferHandler extends TransferHandler {
JTextArea Text;
public FileTransferHandler(JTextArea Text) {
this.Text = Text;
}
public boolean importData(JComponent c, Transferable t) {
try {
List files = (List) t
.getTransferData(DataFlavor.javaFileListFlavor);
addFilesToFilePathList(files);
return true;
} catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public boolean canImport(JComponent c, DataFlavor[] flavors) {
for (int i = 0; i < flavors.length; i++) {
if (DataFlavor.javaFileListFlavor.equals(flavors[i])) {
return true;
}
}
return false;
}
private void addFilesToFilePathList(List files) {
for (Iterator iter = files.iterator(); iter.hasNext();) {
File file = (File) iter.next();
String str = null;
try {
FileReader fr = new FileReader(file);
BufferedReader bfr = new BufferedReader(fr);
Text.setText("");
while ((str = bfr.readLine()) != null) {
Text.append(str + "/15/12");
}
} catch (Exception b) {
}
}
}
}