62,630
社区成员
发帖
与我相关
我的任务
分享
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Font f1 = showField.getFont();
int style = f1.getStyle();
int size = Integer.parseInt((String) jb2.getSelectedItem());
Font f2 = new Font("宋体", style, size);
textArea.setFont(f2);
if ("下划线".equals((String) jb1.getSelectedItem())) {
HashMap<TextAttribute, Object> hm = new HashMap<TextAttribute, Object>();
hm.put(TextAttribute.UNDERLINE,TextAttribute.UNDERLINE_ON); // 定义是否有下划线
hm.put(TextAttribute.SIZE, size); // 定义字号
hm.put(TextAttribute.FAMILY, "宋体"); // 定义字体名
f2 = new Font(hm);
textArea.setFont(new Font(hm));
}
fontDialog.dispose();
}
});
//------------------------------------------------------------------------------------
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
fontDialog.dispose();
}
});
//-------------------------------------------------------------------------------------
} else if("字体颜色".equals(id)){
color = JColorChooser.showDialog(NoteBook.this,"字体颜色设置",color);
textArea.setForeground(color);
} else if("系统 记事本".equals(id)){
String commond = "notepad.exe";
try {
Process child = Runtime.getRuntime().exec(commond);
} catch (Exception e1) { }
} else if("系统 计算器".equals(id)){
String commond = "calc.exe";
try {
Process child = Runtime.getRuntime().exec(commond);
} catch (Exception e1) { }
} else if("任务 管理器".equals(id)){
String commond = "taskmgr.exe";
try {
Process child = Runtime.getRuntime().exec(commond);
} catch (Exception e1) { }
}
}
};
/**
* 要退出记事本,有三种情况
* 一:文本内容不是空,且没有被保存过,这个时候应该弹出保存的对话框让用户保存,然后退出
* 二:文本内容不是空,被保存过,且保存之后内容发生了改变,这个时候直接把文本保存到原来的路径
* 三:文本内容是空,直接退出
*
*/
void exitNoteBook(){
String s2 = textArea.getText();
//文本内容发生改变,且没有被保存过
if (!s1.equals(s2) && file == null) {
JOptionPane op = new JOptionPane(null,
JOptionPane.QUESTION_MESSAGE);
int result = op.showConfirmDialog(null, "文件内容已经改变,是否要保存?");
if (result == op.YES_OPTION) {
saveDialog();
System.exit(1);
} else if (result == op.CANCEL_OPTION) {
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
} else if (result == op.NO_OPTION) {
System.exit(1);
}
//文本内容发生改变,曾经被保存过
} else if (!s1.equals(s2) && file != null) {
JOptionPane op = new JOptionPane(null,
JOptionPane.QUESTION_MESSAGE);
int result = op.showConfirmDialog(null, "文件内容已经改变,是否要保存?");
if (result == op.YES_OPTION) {
saveFile();
System.exit(1);
} else if (result == op.CANCEL_OPTION) {
} else if (result == op.NO_OPTION) {
System.exit(1);
}
} else {
System.exit(1);
}
}
//先弹出提示框,然后保存文件
void saveDialog(){
int returnVal = fileChooser.showSaveDialog(NoteBook.this);
if(returnVal == JFileChooser.APPROVE_OPTION){
file = fileChooser.getSelectedFile();
saveFile();
JOptionPane.showMessageDialog(null, "已经保存!");
}
}
/**
* 文件的保存
*/
void saveFile(){
try {
FileWriter fw = new FileWriter(file);
fw.write(textArea.getText());
fw.close();
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "保存文件出错", "提示", JOptionPane.ERROR_MESSAGE);
}
}
/**
* 文件的打开
*/
void openFile(){
char[] buffer;
try {
FileReader fr = new FileReader(file);
int len = (int)file.length();
buffer = new char[len];
fr.read(buffer, 0, len);
fr.close();
textArea.setText(new String(buffer));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new NoteBook();
System.gc();
}
}
} else if("替换".equals(id)){
final JDialog replaceDialog = new JDialog();
Container pane = replaceDialog.getContentPane();
replaceDialog.setVisible(true);
replaceDialog.setSize(320, 140);
replaceDialog.setLocation(360, 300);
replaceDialog.setAlwaysOnTop(true);
replaceDialog.setResizable(false);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,1));
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JLabel jl1 = new JLabel("查找");
JLabel jl2 = new JLabel("替换");
final JTextField textField1 = new JTextField(15);
final JTextField textField2 = new JTextField(15);
JButton find = new JButton("查找 ");
JButton replace = new JButton("替换 ");
JButton allReplace = new JButton("全部替换");
JButton cancel = new JButton("取消");
panel1.add(jl1);panel1.add(textField1);
panel2.add(jl2);panel2.add(textField2);
panel3.add(find);panel3.add(replace);
panel3.add(allReplace);panel3.add(cancel);
panel.add(panel1);
panel.add(panel2);
panel.add(panel3);
pane.add(panel);
//----------------------------------注册查找事件
find.addActionListener(new ActionListener() {
int fromIndex = 0;
public void actionPerformed(ActionEvent e) {
String s = textField1.getText();
int index = textArea.getText().indexOf(s, fromIndex);
int length = s.length();
fromIndex = index + length;
if (index == -1) {
JOptionPane.showMessageDialog(replaceDialog, "没有找到你要找的内容",
"警告!", JOptionPane.ERROR_MESSAGE);
fromIndex = 0;
} else {
textArea.select(index, index + length);
}
}
});
//----------------------------------单个字符的替换
replace.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if("".equals(textField1.getText())){
JOptionPane.showMessageDialog(replaceDialog, "替换内容失败!",
"警告!", JOptionPane.ERROR_MESSAGE);
} else {
textArea.replaceSelection(textField2.getText());
}
}
});
// ---------------------------------实现所有替换
allReplace.addActionListener(new ActionListener() {
int fromIndex = 0;
int index = 0;
public void actionPerformed(ActionEvent e) {
//文本框为空,则替换失败
if("".equals(textArea.getText()) || "".equals(textField1.getText())
|| "".equals(textField2.getText())){
JOptionPane.showMessageDialog(replaceDialog, "替换内容失败!",
"警告!", JOptionPane.ERROR_MESSAGE);
} else {
while (true) {
String s = textField1.getText();
index = textArea.getText().indexOf(s, fromIndex);
int length = s.length();
fromIndex = index + length;//更新查找的位置
if (index == -1 )
break;
textArea.replaceRange(textField2.getText(), index,
index + length);//把当前查找到的字符串替换掉
}
JOptionPane.showMessageDialog(replaceDialog, "全部替换完毕!");
}
}
});
//------------------------------------注册取消事件
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
replaceDialog.dispose();
}
});
} else if("全选".equals(id)){
textArea.selectAll();
} else if("时间/日期".equals(id)){
Calendar cal = Calendar.getInstance();//获得系统当前时间
Formatter fmt = new Formatter();//设置时间显示格式
fmt.format("%tF %tT", cal,cal);
int position = textArea.getCaretPosition();//获取当前鼠标位置
textArea.insert(fmt.toString(), position); //插入到文本区域中
} else if("撤销".equals(id)){
try {
if(undo.canUndo() == true)//判断上一步操作是否是可以撤销的
undo.undo();
} catch (Exception e1) {
e1.printStackTrace();
}
} else if("自动换行".equals(id)){
if(jcbmi.getState()){
textArea.setLineWrap(true);
}else{
textArea.setLineWrap(false);
}
} else if("字体".equals(id)){
final JDialog fontDialog = new JDialog();
Container pane = fontDialog.getContentPane();
pane.setLayout(new GridLayout(3, 1));
fontDialog.setSize(210, 220);
fontDialog.setLocation(360, 300);
fontDialog.setVisible(true);
fontDialog.setTitle("设置字体");
fontDialog.setResizable(false);
fontDialog.setAlwaysOnTop(true);
JPanel panel1 = new JPanel();
JLabel label1 = new JLabel("字型", JLabel.RIGHT);
JLabel label2 = new JLabel("大小", JLabel.LEFT);
final JComboBox jb1 = new JComboBox();
final JComboBox jb2 = new JComboBox();
jb1.addItem("常规");
jb1.addItem("粗体");
jb1.addItem("斜体");
jb1.addItem("粗斜体");
jb1.addItem("下划线");
jb2.addItem("22");
jb2.addItem("8");
jb2.addItem("12");
jb2.addItem("16");
jb2.addItem("30");
jb2.addItem("40");
panel1.add(label1);
panel1.add(jb1);
panel1.add(label2);
panel1.add(jb2);
JPanel panel2 = new JPanel();
JButton ok = new JButton("确定");
JButton cancel = new JButton("取消");
panel2.add(ok);
panel2.add(cancel);
JPanel panel3 = new JPanel();
panel3.setLayout(new BorderLayout());
JLabel label3 = new JLabel("预览:");
String showStr = "记事本 !";
final JTextArea showField = new JTextArea(showStr);
showField.setFont(new Font("宋体",Font.BOLD,22));
showField.setEditable(false);
panel3.add(label3, BorderLayout.WEST);
panel3.add(showField, BorderLayout.CENTER);
pane.add(panel1);
pane.add(panel2);
pane.add(panel3);
//------------------------------------------------------------------------------------
jb1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int style = Font.BOLD;
String s1 = (String)jb1.getSelectedItem();
String s2 = (String)jb2.getSelectedItem();
int fontSize = Integer.parseInt(s2);
if("常规".equals(s1)){
style = Font.PLAIN;
} else if("粗体".equals(s1)){
style = Font.BOLD;
} else if("斜体".equals(s1)){
style = Font.ITALIC;
} else if("粗斜体".equals(s1)){
style = Font.BOLD + Font.ITALIC;
}
System.out.println(s2);
Font f = new Font("宋体",style,fontSize);
showField.setFont(f);
if("下划线".equals(s1)){
HashMap<TextAttribute, Object> hm = new HashMap<TextAttribute, Object>();
hm.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); // 定义是否有下划线
hm.put(TextAttribute.SIZE, fontSize); // 定义字号
hm.put(TextAttribute.FAMILY, "宋体"); // 定义字体名
f = new Font(hm);
showField.setFont(f);
}
}
}
);
// ----------------------------------------------------------------------------------
jb2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int style = Font.BOLD;
String s1 = (String) jb1.getSelectedItem();
String s2 = (String) jb2.getSelectedItem();
int fontSize = Integer.parseInt(s2);
System.out.println(s2);
Font f = new Font("宋体", style, fontSize);
showField.setFont(f);
if ("下划线".equals(s1)) {
HashMap<TextAttribute, Object> hm = new HashMap<TextAttribute, Object>();
hm.put(TextAttribute.UNDERLINE,
TextAttribute.UNDERLINE_ON); // 定义是否有下划线
hm.put(TextAttribute.SIZE, fontSize); // 定义字号
hm.put(TextAttribute.FAMILY, "宋体"); // 定义字体名
f = new Font(hm);
showField.setFont(f);
}
}
}
);
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.font.TextAttribute;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.Formatter;
import java.util.HashMap;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
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.undo.UndoManager;
/*
* @author admin
* @version 1.0
*/
public class NoteBook extends JFrame {
private static final long serialVersionUID = 1L;
/**textArea 文本区域*/
private JTextArea textArea = new JTextArea();
/**scroll 给文本区域增加的滚动条*/
private JScrollPane scroll;
/**menuBar 菜单条*/
private JMenuBar menuBar;
/**fileChooser 文件选择框*/
private JFileChooser fileChooser = new JFileChooser();
private File file = null;
private String s1 = textArea.getText();
private UndoManager undo = new UndoManager();
/**jcbmi 带选择的菜单子项*/
private JCheckBoxMenuItem jcbmi = new JCheckBoxMenuItem("自动换行", true);
private Color color = Color.black;
private JMenuItem statusBar = new JMenuItem("状态栏");
/**printerJob 打印机*/
private PrinterJob printerJob = PrinterJob.getPrinterJob();
//本类的构造函数
public NoteBook(){
super("记事本");
initTextPane();//初始化面板
initpopMenus();//初始化鼠标右键菜单
initMenu();//初始化标题栏菜单
//窗口注册退出事件
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
exitNoteBook();
}
});
}
/**
* 初始化面板
*/
void initTextPane(){
//构造带滚动条的文本区域
scroll = new JScrollPane(textArea);
add(scroll);
//设置文本区域能够自动换行
textArea.setLineWrap(true);
textArea.setFont(new Font("宋体",Font.BOLD,22));
textArea.getDocument().addUndoableEditListener(undo);//注册撤销事件
textArea.setForeground(Color.blue);//设置背景颜色
statusBar.setEnabled(false);//状态栏不可编辑
setSize(600, 600);
setLocation(230, 100);
setVisible(true);
}
JPopupMenu popupMenus = new JPopupMenu();//鼠标右键菜单
JMenuItem[] popupMenuitems = new JMenuItem[]{//鼠标右键菜单子项
new JMenuItem("撤销"),
new JMenuItem("--"),
new JMenuItem("剪切"),
new JMenuItem("复制"),
new JMenuItem("粘贴"),
new JMenuItem("删除"),
new JMenuItem("--"),
new JMenuItem("全选"),
};
/**
* 初始化鼠标右键菜单
*/
void initpopMenus(){
for(int i=0; i<popupMenuitems.length; i++){
if("--".equalsIgnoreCase(popupMenuitems[i].getText())){
popupMenus.addSeparator();//添加分割符
} else {
popupMenus.add(popupMenuitems[i]);
popupMenuitems[i].addActionListener(action);
}
}
textArea.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
int mods = e.getModifiers();
if((mods&InputEvent.BUTTON3_MASK) != 0){
popupMenus.show(e.getComponent(), e.getX(), e.getY());
}
}
}
);
}
JMenu[] menus = new JMenu[] { //构造菜单
new JMenu("文件"),
new JMenu("编辑"),
new JMenu("格式"),
new JMenu("查看"),
new JMenu("工具"),
new JMenu("帮助"),
};
JMenuItem[][] menuitems = new JMenuItem[][]{//添加菜单子项
{
new JMenuItem("新建"),
new JMenuItem("打开"),
new JMenuItem("保存"),
new JMenuItem("另存为"),
new JMenuItem("--"),
new JMenuItem("页面设置"),
new JMenuItem("打印"),
new JMenuItem("--"),
new JMenuItem("退出")
},
{
new JMenuItem("撤销"),
new JMenuItem("--"),
new JMenuItem("剪切"),
new JMenuItem("复制"),
new JMenuItem("粘贴"),
new JMenuItem("删除"),
new JMenuItem("--"),
new JMenuItem("查找"),
new JMenuItem("替换"),
new JMenuItem("--"),
new JMenuItem("全选"),
new JMenuItem("时间/日期")
},
{
jcbmi,
new JMenuItem("字体"),
new JMenuItem("字体颜色")
},
{
statusBar
},
{
new JMenuItem("系统 记事本"),
new JMenuItem("系统 计算器"),
new JMenuItem("任务 管理器")
},
{
new JMenuItem("关于"),
}
};
void initMenu() {//初始化菜单
menuBar = new JMenuBar();
for (int i = 0; i < menus.length; i++) {
menuBar.add(menus[i]);
for (int j = 0; j < menuitems[i].length; j++) {
if ("--".equalsIgnoreCase(menuitems[i][j].getText())) {
menus[i].addSeparator();//添加分隔符号
} else {
menus[i].add(menuitems[i][j]);
menuitems[i][j].addActionListener(action);
}
}
}
this.add(menuBar, BorderLayout.NORTH);
}
/**
* 事件处理,运用了内部类来完成时间的处理
*/
ActionListener action = new ActionListener(){
public void actionPerformed(ActionEvent e) {
JMenuItem mi = (JMenuItem)e.getSource();
String id = mi.getText();
if("新建".equals(id)){
String s2 = textArea.getText();
//如果文本内容被改变,且文件没有被保存过,则调用saveDialog()
if (!s1.equals(s2) && file == null) {
JOptionPane op = new JOptionPane(null,
JOptionPane.QUESTION_MESSAGE);
int result = op.showConfirmDialog(null, "文件内容已经改变,是否要保存?");
if (result == op.YES_OPTION) {
saveDialog();
textArea.setText("");
} else if (result == op.CANCEL_OPTION) {
} else if (result == op.NO_OPTION) {
textArea.setText("");
}
//如果文本内容被改变,且文件被保存过,则调用saveFile()
} else if (!s1.equals(s2) && file != null) {
JOptionPane op = new JOptionPane(null,
JOptionPane.QUESTION_MESSAGE);
int result = op.showConfirmDialog(null, "文件内容已经改变,是否要保存?");
if (result == op.YES_OPTION) {
saveFile();
textArea.setText("");
} else if (result == op.CANCEL_OPTION) {
} else if (result == op.NO_OPTION) {
textArea.setText("");
}
//如果文本内容没有被改变过,则刷新当前文本
} else {
textArea.setText("");
}
//调用openFile()
} else if ("打开".equals(id)) {
int returnVal = fileChooser.showOpenDialog(NoteBook.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fileChooser.getSelectedFile();
openFile();
}
//如果文件被保存过,调用saveFile();如果没有被保存过,则调用saveDialog()
} else if("保存".equals(id)){
if(file != null){
saveFile();
}else{
saveDialog();
}
//调用saveDialog()
} else if("另存为".equals(id)){
saveDialog();
} else if("页面设置".equals(id)){
printerJob.printDialog();
} else if("打印".equals(id)){
try {
printerJob.print();
} catch(Exception ew){
JOptionPane.showMessageDialog(NoteBook.this,"打印出错!","错误",JOptionPane.ERROR_MESSAGE);
}
}
//调用退出文本的方法
else if ("退出".equals(id)) {
exitNoteBook();
} else if("复制".equals(id)){
textArea.copy();
} else if("粘贴".equals(id)){
textArea.paste();
} else if("剪切".equals(id)){
textArea.cut();
} else if("删除".equals(id)){
textArea.replaceSelection("");
} else if ("查找".equals(id)) {
final JDialog findDialog = new JDialog();
Container pane = findDialog.getContentPane();
findDialog.setSize(310, 80);
findDialog.setLocation(360, 300);
findDialog.setVisible(true);
findDialog.setTitle("查找");
findDialog.setAlwaysOnTop(true);
JPanel panel = new JPanel();
final JTextField textField = new JTextField(10);
JButton next = new JButton("下一个");
JButton cancel = new JButton("取消 ");
panel.add(textField);
panel.add(next);
panel.add(cancel);
pane.add(panel);
//-------------------------------注册“下一个”按钮事件
next.addActionListener(new ActionListener() {
int fromIndex = 0;
public void actionPerformed(ActionEvent e) {
String s = textField.getText();//获取要查找的字符串
int index = textArea.getText().indexOf(s, fromIndex);//娶得要查找字符串在文本区域出现的位置
int length = s.length();
fromIndex = index + length;//更新查找的位置
if (index == -1) {
JOptionPane.showMessageDialog(findDialog, "没有找到你要找的内容",
"警告!", JOptionPane.ERROR_MESSAGE);
fromIndex = 0;
textArea.requestFocus();
} else {
textArea.select(index, index + length);//选中查找的内容
textArea.setSelectionColor(Color.green);//设置字体颜色
}
}
});
//------------------------------注册取消事件
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
findDialog.dispose();
}
}
);