文本编辑器EditPlus

来源:互联网 发布:linux ps -ef|grep命令 编辑:程序博客网 时间:2024/05/29 10:56

程序运行图片:

/** * @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();// 把各组件的字体设置为menufontthis.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() {@Overridepublic void actionPerformed(ActionEvent e) {if (jmtlinewrap.isSelected()) {jta.setLineWrap(true);// 设置为自动换行} else {jta.setLineWrap(false);// 设置为不自动换行}}});jmtabout.addActionListener(new ActionListener() {@Overridepublic 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);// 创建JToolBarjtb = new JToolBar();jtb.setLayout(new FlowLayout(FlowLayout.LEFT));// 创建JTextAreajta = 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")@Overridepublic void mouseEntered(MouseEvent e) {EditPlus.this.setCursor(Cursor.CROSSHAIR_CURSOR);// 设置鼠标样式为文本编辑样式}@SuppressWarnings("deprecation")@Overridepublic void mouseExited(MouseEvent e) {EditPlus.this.setCursor(Cursor.DEFAULT_CURSOR);// 设置鼠标样式为默认样式}@Overridepublic void mouseReleased(MouseEvent e) {}@Overridepublic void mousePressed(MouseEvent e) {}});jta.addCaretListener(new CaretListener() {@Overridepublic void caretUpdate(CaretEvent e) {isUpdated = true;stastic = jta.getText().trim().toString().length();// 除去空格和换行符都计数jlstastic.setText("字数:" + stastic);// TODO}});// 创建面板1GraphicsEnvironment 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);// 创建面板2p2 = 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);// 创建面板3p3 = 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() {@Overridepublic 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() {@Overridepublic 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添加到面板的北边// 创建统计字数的JLabeljlstastic = new JLabel("字数:" + stastic);jlstastic.setBackground(Color.WHITE);jlstastic.setOpaque(true);this.getContentPane().add(jlstastic, "South");// 创建JPopupMenupopmenu = 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() {@Overridepublic 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);}}@Overridepublic void windowOpened(WindowEvent e) {}@Overridepublic void windowClosed(WindowEvent e) {}@Overridepublic void windowIconified(WindowEvent e) {}@Overridepublic void windowDeiconified(WindowEvent e) {}@Overridepublic void windowActivated(WindowEvent e) {}@Overridepublic void windowDeactivated(WindowEvent e) {}});this.getContentPane().add(new JScrollPane(jta));// 添加带滚动条的JTextAreathis.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() {@Overridepublic 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();}}


0 0
原创粉丝点击