/** * */ package cross.pauliuyou.io; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.MouseInfo; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Vector; import javax.swing.ButtonGroup; import javax.swing.JFileChooser; import javax.swing.JFrame; 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.JRadioButtonMenuItem; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; /** * 文件编辑器 * * @author 刘优 * @version 1.0 * */ public class FileEditor extends JFrame implements ActionListener, MouseListener, KeyListener, ChangeListener { /** * */ private static final long serialVersionUID = 1L; private static final String previousOpenDirectory = "FileEditor_PreviousOpenedDirectory"; private static final String previousOpenedFiles = "FileEditor_PreviousOpenedFiles"; private static final String historyListFileName = "FileEditor_HistoryList"; private static NormalFileInfor previousOpenDirectoryInfor; private static NormalFileInfor previousOpenedFilesInfor; private static NormalFileInfor historyListFileNameInfor; static { try { previousOpenDirectoryInfor = new NormalFileInfor( previousOpenDirectory); } catch (IOException e) { e.printStackTrace(); } try { previousOpenedFilesInfor = new NormalFileInfor(previousOpenedFiles); } catch (IOException e) { e.printStackTrace(); } try { historyListFileNameInfor = new NormalFileInfor(historyListFileName); } catch (IOException e) { e.printStackTrace(); } } public boolean isStandAloneProcess = false; private int histroyListCount = 20; private Vector fileInfors = new Vector(); /** * 可切换画面控件 */ private JTabbedPane tabbedPane = new JTabbedPane(); private int newFileCount; private Vector allTextAreas = new Vector(); private Vector allTextPanels = new Vector(); private Vector allFilePropertyTextFields = new Vector(); private Dimension screenDimension; private String closeFileCommandHead = "closefile_"; private JPopupMenu showFileOperationPopMenu; private JMenuItem closeFileMenuItem; private String previousPath = null; private JRadioButtonMenuItem normalMenuItem = new JRadioButtonMenuItem(); private JRadioButtonMenuItem hexMenuItem = new JRadioButtonMenuItem(); private int tabSize = 8; private JRadioButtonMenuItem[] encodeMenuItems; private int encodeTypeCount; private static final String titleHead = "文件编辑器 - "; private int currentIndex; private FileInfor currentFileInfor; private JTextArea currentTextArea; private JPanel currentTextPanel; private JTextField currentPropertyText; private JMenuItem defaultFileEncodeMenuItem; private JMenuItem setFileEncodeMenuItem; private JMenu historyMenu; private boolean isFrameInited; private byte[] tempBuf = new byte[100]; public FileEditor() { addEmptyNewFile(); thisFrameInit(); } public FileEditor(String fileName) { if (fileName == null) { addEmptyNewFile(); } else { String[] fileNames = fileName.split(","); File[] theFiles = new File[fileNames.length]; for (int i = 0; i < fileNames.length; i++) { theFiles[i] = new File(fileNames[i]); } setFiles(theFiles); } thisFrameInit(); } public FileEditor(String[] fileNames) { setFileNames(fileNames); thisFrameInit(); } public FileEditor(File file) { this(new File[] { file }); } public FileEditor(File[] files) { setFiles(files); thisFrameInit(); } /** * */ private File[] confirmFilesToOpen() { String openFileDialogBeginPath = null; if (currentIndex != -1 && currentFileInfor instanceof NormalFileInfor) { openFileDialogBeginPath = ((NormalFileInfor) currentFileInfor) .getFile().getParentFile().getAbsolutePath(); } else { if (previousPath == null) { try { previousPath = previousOpenDirectoryInfor.readSimple(); } catch (Exception ex) { previousPath = "."; } } openFileDialogBeginPath = previousPath; } JFileChooser fileChooser = new JFileChooser(openFileDialogBeginPath); fileChooser.setMultiSelectionEnabled(true); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int rs = fileChooser.showOpenDialog(this); if (rs == 0) { File[] theFiles = fileChooser.getSelectedFiles(); if (theFiles != null && theFiles.length > 0) { String thisPath = theFiles[0].getParent(); if (!thisPath.equals(previousPath)) { previousPath = thisPath; try { previousOpenDirectoryInfor.writeSimple(previousPath); } catch (IOException e) { e.printStackTrace(); } } } return theFiles; } return null; } private File confirmFilesToSave() { String openFileDialogBeginPath = null; if (currentIndex != -1 && currentFileInfor instanceof NormalFileInfor) { openFileDialogBeginPath = ((NormalFileInfor) currentFileInfor) .getFile().getParentFile().getAbsolutePath(); } else { if (previousPath == null) { try { previousPath = previousOpenDirectoryInfor.readSimple(); } catch (IOException ex) { previousPath = "."; } } openFileDialogBeginPath = previousPath; } JFileChooser fileChooser = new JFileChooser(openFileDialogBeginPath); fileChooser.setMultiSelectionEnabled(false); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setSelectedFile(new File(openFileDialogBeginPath, currentFileInfor.getName())); int rs = fileChooser.showSaveDialog(this); if (rs == 0) { File theFile = fileChooser.getSelectedFile(); if (theFile != null) { String thisPath = theFile.getParent(); if (!thisPath.equals(previousPath)) { previousPath = thisPath; try { previousOpenDirectoryInfor.writeSimple(previousPath); } catch (IOException e) { e.printStackTrace(); } } } return theFile; } else { return null; } } /** * @param fileNames */ private void setFileNames(String[] fileNames) { File[] theFiles = new File[fileNames.length]; for (int i = 0; i < fileNames.length; i++) { theFiles[i] = new File(fileNames[i]); } setFiles(theFiles); } /** * @param files2 * @throws */ private void setFiles(File[] theFiles) { if (theFiles == null || theFiles.length == 0) { addEmptyNewFile(); } else { for (int i = 0; i < theFiles.length; i++) { addFile(theFiles[i]); } } } /** * */ private void addEmptyNewFile() { if (!isFrameInited) { boolean hasPrevious = true; try { if (previousOpenedFilesInfor.getLength() == 0) { hasPrevious = false; } else { List openedFiles = previousOpenedFilesInfor.readToListSimple(); if (openedFiles == null || openedFiles.size() == 0) { hasPrevious = false; } else { File[] theFiles = new File[openedFiles.size()]; for (int i = 0; i < openedFiles.size(); i++) { theFiles[i] = new File(openedFiles.get(i).toString()); } setFiles(theFiles); } } } catch (IOException e1) { hasPrevious = false; } if (hasPrevious) { return; } } String content = ""; allTextPanels.add(createFileAreaPanel(content, null)); String newFileName = "新文件" + (++newFileCount); tabbedPane.add(newFileName, (JPanel)allTextPanels.get(allTextPanels.size() - 1)); try { fileInfors.add(new EmptyInfor(newFileName)); setTabbedPaneToLast(); } catch (IOException e) { e.printStackTrace(); } } public void addFile(File file) { int index = -1; for (int i = 0; i < fileInfors.size(); i++) { if (((FileInfor)fileInfors.get(i)).getPath().equals(file.getAbsolutePath())) { index = i; break; } } if (index != -1) { setTabbedPane(index); return; } String infors = ""; try { NormalFileInfor infor = new NormalFileInfor(file); if (!isFrameInited && infor.isNewCreatedFile()) { MsgBox.msg(this, "文件 [" + infor.getPath() + "] 已经被删除"); return; } fileInfors.add(infor); String fileContent = null; if (infor.isBinary()) { fileContent = infor.getHexDisplay(); } else { fileContent = infor.getNormalDisplay(); } String fileDetail = infor.getPropertyString(); tabbedPane.add(file.getName(), createFileAreaPanel(fileContent, fileDetail)); setTabbedPaneToLast(); addFileNameToHistoryListHead(infor.getPath()); } catch (IOException e1) { infors += e1.toString() + "/n"; MsgBox.error(this, infors); } } private void addFileNameToHistoryListHead(String filePath) throws IOException { if (!new File(filePath).exists()) { return; } List histroyFileNames = null; try { histroyFileNames = historyListFileNameInfor.readToListSimple(); } catch (Exception ex) { } if (histroyFileNames == null) { histroyFileNames = new Vector(); } while (true) { boolean hasEmpty = false; for (int i = 0; i < histroyFileNames.size(); i++) { if (!new File(histroyFileNames.get(i).toString()).exists()) { hasEmpty = true; histroyFileNames.remove(i); break; } } if (!hasEmpty) { break; } } if (histroyFileNames.contains(filePath)) { histroyFileNames.remove(filePath); } if (histroyFileNames.size() > histroyListCount) { histroyFileNames.remove(histroyFileNames.size() - 1); } histroyFileNames.add(0, filePath); historyListFileNameInfor.writeListSimple(histroyFileNames); } /** * */ private void setTabbedPaneToLast() { int lastIndex = fileInfors.size() - 1; setTabbedPane(lastIndex); } /** * @param index */ private void setTabbedPane(int index) { currentIndex = index; if (index < 0 || index >= fileInfors.size()) { // MsgBox.alert(this,"索引 [" + index + "] 超出范围,请检查"); setTitle(titleHead); return; } tabbedPane.setSelectedIndex(index); currentFileInfor = (FileInfor)fileInfors.get(currentIndex); currentTextArea = (JTextArea)allTextAreas.get(currentIndex); currentTextPanel = (JPanel)allTextPanels.get(currentIndex); currentTextPanel.getAutoscrolls(); currentPropertyText = (JTextField)allFilePropertyTextFields.get(currentIndex); setTitle(titleHead + "[" + currentFileInfor.getPath() + "]"); currentTextArea.setCaretPosition(0); if (currentFileInfor.isHexMode()) { hexMenuItem.setSelected(true); } else { normalMenuItem.setSelected(true); } fixFileEncodeMenus(); } /** * */ private void fixFileEncodeMenus() { if (encodeMenuItems == null) { return; } String theEncode = currentFileInfor.getEncode(); if (theEncode == null || currentFileInfor instanceof EmptyInfor) { encodeMenuItems[Encoding.UTF8].setSelected(true); return; } if ("BINARY".equals(theEncode)) { encodeMenuItems[encodeTypeCount - 1].setSelected(true); return; } for (int i = 0; i < encodeTypeCount; i++) { String label = encodeMenuItems[i].getText(); if (label.equals(theEncode)) { encodeMenuItems[i].setSelected(true); break; } } } /** * */ private void thisFrameInit() { getMenu(); setTabbedPaneToLast(); tabbedPane.addMouseListener(this); this.getContentPane().add(tabbedPane); screenDimension = Toolkit.getDefaultToolkit().getScreenSize(); // 将本窗口全屏化 this.setSize(screenDimension.width, screenDimension.height - 30); this.setExtendedState(JFrame.MAXIMIZED_BOTH); setLocation(0, 0); setVisible(true); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { shutdown(); } }); isFrameInited = true; } /** * @param string * @return */ private JPanel createFileAreaPanel(String fileContent, String detail) { JPanel filePanel = new JPanel(); JTextArea textArea = null; textArea = new JTextArea(fileContent); textArea.setTabSize(tabSize); textArea.addKeyListener(this); allTextAreas.add(textArea); if (detail == null) { detail = ""; } JTextField fileDetailText = new JTextField(detail); fileDetailText.setEditable(false); allFilePropertyTextFields.add(fileDetailText); filePanel.setLayout(new BorderLayout()); filePanel.add(new JScrollPane(textArea)); filePanel.add(fileDetailText, "South"); allTextPanels.add(filePanel); return filePanel; } private void shutdown() { this.dispose(); Vector newContent = new Vector(); for (int i = 0; i < fileInfors.size(); i++) { FileInfor infor = (FileInfor)fileInfors.get(i); if (infor instanceof NormalFileInfor) { newContent.add(infor.getPath()); } } try { previousOpenedFilesInfor.writeListSimple(newContent); } catch (IOException e) { e.printStackTrace(); } } /** * */ private void showAbout() { MsgBox.msg(this, "文件编辑器 V1.0 /n作者 刘优"); } /* * (non-Javadoc) * * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent) */ public void mouseClicked(MouseEvent event) { if (event.getSource() instanceof JTabbedPane) { // System.out.println(event.getButton()); if (event.getClickCount() == 2 && event.getButton() == MouseEvent.BUTTON1) { closeCurrent(); setTabbedPaneToLast(); return; } // 响应鼠标右键 if (event.getButton() == MouseEvent.BUTTON3) { closeFileMenuItem.setActionCommand(this.closeFileCommandHead + tabbedPane.getSelectedIndex()); Point mousePoint = MouseInfo.getPointerInfo().getLocation(); this.showFileOperationPopMenu.setLocation(mousePoint); showFileOperationPopMenu.setVisible(true); // MsgBox.msg(this,name); } setTabbedPane(tabbedPane.getSelectedIndex()); } } /** * */ private void closeCurrent() { int currentIndex = tabbedPane.getSelectedIndex(); this.closeFile(currentIndex); } /* * (non-Javadoc) * * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent) */ public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent) */ public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent) */ public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent) */ public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent) */ public void keyPressed(KeyEvent event) { if (!checkIndex()) { return; } int keyCode = event.getKeyCode(); if (event.isControlDown()) { if (keyCode == 83) { return; } } else { if (keyCode == '/n') { if (currentFileInfor.isHexMode()) { String[] lines = currentTextArea.getText().trim().split( "/n"); String lastLine = lines[lines.length - 1]; try { FileInfor.hexLineToByteArray(lastLine, tempBuf); String hexHead = FileInfor .fillZeroForNumber(lines.length * FileInfor.byteNumberPerLine) + FileInfor.addressSeperator; currentTextArea.append('/n' + hexHead); } catch (IOException e) { MsgBox.error("十六进制数据行 [" + lastLine + "]/n有错误 : [" + e.getMessage() + "]"); } } } String oldTitle = tabbedPane.getTitleAt(currentIndex); if (!oldTitle.startsWith("*")) { currentFileInfor.setDirty(true); oldTitle = "*" + oldTitle; tabbedPane.setTitleAt(currentIndex, oldTitle); } } } /* * (non-Javadoc) * * @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent) */ public void keyReleased(KeyEvent event) { int keyCode = event.getKeyCode(); if (keyCode == '/n') { if (currentFileInfor.isHexMode()) { String theText = currentTextArea.getText(); if (theText.length() > 0) { currentTextArea.setText(theText.substring(0, theText .length() - 1)); } } // currentTextArea.setCaretPosition(currentTextArea.getCaretPosition() // - 1); } } /* * (non-Javadoc) * * @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent) */ public void keyTyped(KeyEvent event) { } /** * */ private boolean checkIndex() { return currentIndex >= 0 && currentIndex < tabbedPane.getComponentCount(); } /* * (non-Javadoc) * * @see javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent) */ public void stateChanged(ChangeEvent arg0) { // TODO Auto-generated method stub } /** * @param file */ private void closeFile(int fileid) { boolean toRemove = true; FileInfor file = (FileInfor)fileInfors.get(fileid); if (file.isDirty() && !file.isSaved()) { int ask = JOptionPane.showConfirmDialog(this, "文件 " + file.getName() + " 已更改,是否保存?"); // System.out.println(ask); // 是 按纽 if (ask == 0) { if (file instanceof NormalFileInfor) { try { saveFile(fileid); } catch (IOException e) { e.printStackTrace(); MsgBox.error(this, "文件保存失败"); } } else { try { File toSaveFile = saveAsFile(); if (toSaveFile == null) { toRemove = false; } else { file = (FileInfor)fileInfors.get(fileid); } } catch (UnsupportedEncodingException e) { MsgBox.alert(this, "编码设置有错误"); toRemove = false; } catch (Exception e) { MsgBox.alert(this, "文件保存错误"); toRemove = false; } } } if (ask == 2) { toRemove = false; } } if (toRemove) { tabbedPane.remove(fileid); fileInfors.remove(fileid); allTextAreas.remove(fileid); allTextPanels.remove(fileid); try { if (file instanceof NormalFileInfor) { addFileNameToHistoryListHead(file.getPath()); this.adjustHistroyFileListMenu(); } } catch (IOException e) { e.printStackTrace(); } this.setTabbedPaneToLast(); } } /** * @throws FileNotFoundException * @throws UnsupportedEncodingException * */ private File saveEmptyFileInfor() throws UnsupportedEncodingException, FileNotFoundException { File fileToSave = confirmFilesToSave(); if (fileToSave == null) { return null; } if (fileToSave.exists()) { int ask2 = JOptionPane.showConfirmDialog(this, "文件 " + fileToSave.getName() + " 已存在,是否覆盖?"); // System.out.println(ask); // 取消 按纽 if (ask2 == 1 || ask2 == 2) { return null; } } saveCurrentFileTo(fileToSave); return fileToSave; } /** * @param fileToSave * @throws FileNotFoundException * @throws UnsupportedEncodingException */ private void saveCurrentFileTo(File fileToSave) throws UnsupportedEncodingException, FileNotFoundException { String theEncode = "UTF-8"; for (int i = 0; i < encodeTypeCount; i++) { if (encodeMenuItems[i].isSelected()) { theEncode = Encoding.javaname[i]; break; } } writeTextFile(fileToSave, currentTextArea.getText(), theEncode); } public static void writeTextFile(File file, String content, String encode) throws UnsupportedEncodingException, FileNotFoundException { PrintWriter fileWriter = new PrintWriter(new OutputStreamWriter( new FileOutputStream(file), encode)); fileWriter.print(content); fileWriter.close(); } /** * @param fileid * @throws FileNotFoundException */ private void saveFile(int fileid) throws IOException { if (fileid < 0) { return; } FileInfor file = (FileInfor)fileInfors.get(fileid); if (!file.isHexMode()) { file.write(((JTextArea)allTextAreas.get(fileid)).getText()); } else { // save hex String hexString = ((JTextArea)allTextAreas.get(fileid)).getText(); if (hexString != null && !hexString.trim().equals("")) { file.writeHexByString(hexString); } } tabbedPane.setTitleAt(fileid, file.getName()); file.setDirty(false); } /** * @throws IOException * */ private File saveAsFile() throws IOException { File fileToSave = saveEmptyFileInfor(); if (fileToSave != null) { fileInfors.remove(currentIndex); FileInfor infor = new NormalFileInfor(fileToSave); fileInfors.add(currentIndex, infor); this.currentPropertyText.setText(infor.getPropertyString()); this.setTabbedPane(currentIndex); tabbedPane.setTitleAt(currentIndex, infor.getName()); } return fileToSave; } /** * 初始化菜单 * */ private void getMenu() { JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("文 件 (F) "); fileMenu.setMnemonic(KeyEvent.VK_F); JMenu encodeMenu = new JMenu("编 码 (D) "); encodeMenu.setMnemonic(KeyEvent.VK_D); JMenu editMenu = new JMenu("编 辑 (E) "); editMenu.setMnemonic(KeyEvent.VK_E); JMenu searchMenu = new JMenu("搜 索 (S) "); searchMenu.setMnemonic(KeyEvent.VK_S); JMenu viewMenu = new JMenu("视 图 (V) "); viewMenu.setMnemonic(KeyEvent.VK_V); JMenu columnMenu = new JMenu("列模式 (C) "); columnMenu.setMnemonic(KeyEvent.VK_C); JMenu formatMenu = new JMenu("格 式 (T) "); formatMenu.setMnemonic(KeyEvent.VK_T); JMenu advancedMenu = new JMenu("高 级 (A) "); advancedMenu.setMnemonic(KeyEvent.VK_A); JMenu windowMenu = new JMenu("窗 口 (W) "); windowMenu.setMnemonic(KeyEvent.VK_W); JMenu helpMenu = new JMenu("帮 助 (H) "); helpMenu.setMnemonic(KeyEvent.VK_H); JMenuItem newMenuItem = new JMenuItem("新 建 (N)", KeyEvent.VK_N); KeyStroke ctrlNKeyStroke = KeyStroke.getKeyStroke("control N"); newMenuItem.setAccelerator(ctrlNKeyStroke); JMenuItem openMenuItem = new JMenuItem("打 开... (O)", KeyEvent.VK_O); KeyStroke ctrlOKeyStroke = KeyStroke.getKeyStroke("control O"); openMenuItem.setAccelerator(ctrlOKeyStroke); JMenuItem closeMenuItem = new JMenuItem("关 闭 (C)", KeyEvent.VK_C); KeyStroke ctrlQKeyStroke = KeyStroke.getKeyStroke("control Q"); closeMenuItem.setAccelerator(ctrlQKeyStroke); JMenuItem saveMenuItem = new JMenuItem("保 存 (S)", KeyEvent.VK_S); KeyStroke ctrlSKeyStroke = KeyStroke.getKeyStroke("control S"); saveMenuItem.setAccelerator(ctrlSKeyStroke); JMenuItem saveAsMenuItem = new JMenuItem("另存为 (A)", KeyEvent.VK_A); historyMenu = new JMenu("历史文件 (H)"); historyMenu.setMnemonic(KeyEvent.VK_H); JMenuItem exitMenuItem = new JMenuItem("退出程序 (X)", KeyEvent.VK_X); newMenuItem.addActionListener(this); newMenuItem.setActionCommand("newfile"); openMenuItem.addActionListener(this); openMenuItem.setActionCommand("openfile"); closeMenuItem.addActionListener(this); closeMenuItem.setActionCommand("closecurrentfile"); saveMenuItem.addActionListener(this); saveMenuItem.setActionCommand("savefile"); saveAsMenuItem.addActionListener(this); saveAsMenuItem.setActionCommand("saveasfile"); historyMenu.addActionListener(this); historyMenu.setActionCommand("historyfile"); adjustHistroyFileListMenu(); exitMenuItem.addActionListener(this); exitMenuItem.setActionCommand("exitfile"); fileMenu.add(newMenuItem); fileMenu.add(openMenuItem); fileMenu.add(closeMenuItem); fileMenu.addSeparator(); fileMenu.add(saveMenuItem); fileMenu.add(saveAsMenuItem); fileMenu.addSeparator(); fileMenu.add(historyMenu); fileMenu.addSeparator(); fileMenu.add(exitMenuItem); // / JMenuItem undoMenuItem = new JMenuItem("撤 消 (U)", KeyEvent.VK_U); undoMenuItem.addActionListener(this); undoMenuItem.setActionCommand("undoedit"); KeyStroke ctrlZKeyStroke = KeyStroke.getKeyStroke("control Z"); undoMenuItem.setAccelerator(ctrlZKeyStroke); editMenu.add(undoMenuItem); JMenuItem redoMenuItem = new JMenuItem("重 做 (R)", KeyEvent.VK_R); redoMenuItem.addActionListener(this); redoMenuItem.setActionCommand("redoedit"); KeyStroke ctrlYKeyStroke = KeyStroke.getKeyStroke("control Y"); redoMenuItem.setAccelerator(ctrlYKeyStroke); editMenu.add(redoMenuItem); editMenu.addSeparator(); // Edit->Cut, T - Mnemonic, CTRL-X - Accelerator JMenuItem cutMenuItem = new JMenuItem("剪 切 (T)", KeyEvent.VK_T); cutMenuItem.addActionListener(this); cutMenuItem.setActionCommand("cutedit"); KeyStroke ctrlXKeyStroke = KeyStroke.getKeyStroke("control X"); cutMenuItem.setAccelerator(ctrlXKeyStroke); editMenu.add(cutMenuItem); // Edit->Copy, C - Mnemonic, CTRL-C - Accelerator JMenuItem copyMenuItem = new JMenuItem("复 制 (C)", KeyEvent.VK_C); copyMenuItem.addActionListener(this); copyMenuItem.setActionCommand("copyedit"); KeyStroke ctrlCKeyStroke = KeyStroke.getKeyStroke("control C"); copyMenuItem.setAccelerator(ctrlCKeyStroke); editMenu.add(copyMenuItem); // Edit->Paste, P - Mnemonic, CTRL-V - Accelerator, Disabled JMenuItem pasteMenuItem = new JMenuItem("粘 贴 (P)", KeyEvent.VK_P); pasteMenuItem.addActionListener(this); pasteMenuItem.setActionCommand("pasteedit"); KeyStroke ctrlVKeyStroke = KeyStroke.getKeyStroke("control V"); pasteMenuItem.setAccelerator(ctrlVKeyStroke); pasteMenuItem.setEnabled(false); editMenu.add(pasteMenuItem); editMenu.addSeparator(); JMenuItem selectAllMenuItem = new JMenuItem("全 选 (A)", KeyEvent.VK_A); selectAllMenuItem.addActionListener(this); selectAllMenuItem.setActionCommand("selectalledit"); KeyStroke ctrlAKeyStroke = KeyStroke.getKeyStroke("control A"); selectAllMenuItem.setAccelerator(ctrlAKeyStroke); editMenu.add(selectAllMenuItem); JMenuItem deselectAllMenuItem = new JMenuItem("全不选 (B)", KeyEvent.VK_B); deselectAllMenuItem.addActionListener(this); deselectAllMenuItem.setActionCommand("deselectalledit"); editMenu.add(deselectAllMenuItem); // // // 搜索菜单 // searchMenu JMenuItem findMenuItem = new JMenuItem("查 找 (F)", KeyEvent.VK_F); findMenuItem.addActionListener(this); findMenuItem.setActionCommand("findsearch"); KeyStroke ctrlFKeyStroke = KeyStroke.getKeyStroke("control F"); findMenuItem.setAccelerator(ctrlFKeyStroke); searchMenu.add(findMenuItem); JMenuItem previousSearchMenuItem = new JMenuItem("查找上一个 (P)", KeyEvent.VK_P); previousSearchMenuItem.addActionListener(this); previousSearchMenuItem.setActionCommand("previoussearch"); searchMenu.add(previousSearchMenuItem); JMenuItem nextSearchMenuItem = new JMenuItem("查找下一个 (N)", KeyEvent.VK_N); nextSearchMenuItem.addActionListener(this); nextSearchMenuItem.setActionCommand("nextsearch"); searchMenu.add(nextSearchMenuItem); JMenuItem replaceMenuItem = new JMenuItem("替 换 (R)", KeyEvent.VK_R); replaceMenuItem.addActionListener(this); replaceMenuItem.setActionCommand("replacesearch"); KeyStroke ctrlRKeyStroke = KeyStroke.getKeyStroke("control R"); replaceMenuItem.setAccelerator(ctrlRKeyStroke); searchMenu.add(replaceMenuItem); // // // ButtonGroup for radio buttons ButtonGroup directionGroup = new ButtonGroup(); // Edit->Options->Forward, F - Mnemonic, in group normalMenuItem.setText("正常字符"); normalMenuItem.addActionListener(this); normalMenuItem.setActionCommand("normalview"); viewMenu.add(normalMenuItem); directionGroup.add(normalMenuItem); // Edit->Options->Backward, B - Mnemonic, in group hexMenuItem.setText("十六进制"); hexMenuItem.addActionListener(this); hexMenuItem.setActionCommand("hexview"); viewMenu.add(hexMenuItem); directionGroup.add(hexMenuItem); // / // encodeMenu; defaultFileEncodeMenuItem = new JMenuItem("使用默认编码"); defaultFileEncodeMenuItem.addActionListener(this); defaultFileEncodeMenuItem.setEnabled(false); defaultFileEncodeMenuItem.setActionCommand("setdefaultfileencode"); setFileEncodeMenuItem = new JMenuItem("设定文件编码"); setFileEncodeMenuItem.addActionListener(this); setFileEncodeMenuItem.setEnabled(false); setFileEncodeMenuItem.setActionCommand("setfileencode"); encodeMenu.add(defaultFileEncodeMenuItem); encodeMenu.add(setFileEncodeMenuItem); encodeMenu.addSeparator(); encodeTypeCount = Encoding.nicename.length; ButtonGroup directionEncodeGroup = new ButtonGroup(); encodeMenuItems = new JRadioButtonMenuItem[encodeTypeCount]; for (int i = 0; i < encodeTypeCount; i++) { encodeMenuItems[i] = new JRadioButtonMenuItem(Encoding.nicename[i]); encodeMenuItems[i].addActionListener(this); encodeMenuItems[i].setActionCommand("setencode_" + i + "_" + Encoding.javaname[i]); encodeMenu.add(encodeMenuItems[i]); directionEncodeGroup.add(encodeMenuItems[i]); } // /// JMenuItem aboutMenuItem = new JMenuItem("关于本程序", KeyEvent.VK_A); aboutMenuItem.addActionListener(this); aboutMenuItem.setActionCommand("about"); helpMenu.add(aboutMenuItem); menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(encodeMenu); menuBar.add(searchMenu); menuBar.add(viewMenu); menuBar.add(columnMenu); menuBar.add(formatMenu); menuBar.add(advancedMenu); menuBar.add(windowMenu); menuBar.add(helpMenu); this.setJMenuBar(menuBar); // 初始化弹出式菜单 添加在实时数据显示区右键响应菜单 showFileOperationPopMenu = new JPopupMenu("showFileOperationPopMenu"); closeFileMenuItem = new JMenuItem("关闭此文件"); closeFileMenuItem.setActionCommand("closefile_"); closeFileMenuItem.addActionListener(this); JMenuItem tmpMenuItem = new JMenuItem("关闭其他文件"); tmpMenuItem.setActionCommand("closeallotherfiles"); tmpMenuItem.addActionListener(this); JMenuItem tmpMenuItem2 = new JMenuItem("关闭所有文件"); tmpMenuItem2.setActionCommand("closeallfiles"); tmpMenuItem2.addActionListener(this); showFileOperationPopMenu.add(closeFileMenuItem); showFileOperationPopMenu.add(tmpMenuItem); showFileOperationPopMenu.add(tmpMenuItem2); showFileOperationPopMenu.setInvoker(this); } private void adjustHistroyFileListMenu() { historyMenu.removeAll(); List histroyFileNames = null; try { histroyFileNames = historyListFileNameInfor.readToListSimple(); if (histroyFileNames != null && histroyFileNames.size() > 0) { for (int i = 0; i < histroyFileNames.size(); i++) { String historyName = histroyFileNames.get(i).toString(); if (new File(historyName).exists() && !containsFile(historyName)) { JMenuItem item = new JMenuItem(historyName); item.addActionListener(this); item.setActionCommand("showhistory_" + historyName); historyMenu.add(item); } } } } catch (Exception ex) { } } /** * @param historyName * @return */ private boolean containsFile(String fileName) { for (int i = 0; i < fileInfors.size(); i++) { if (((FileInfor)fileInfors.get(i)).getPath().equals(fileName)) { return true; } } return false; } /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent event) { String cmd = event.getActionCommand(); if (cmd.equals("newfile")) { addEmptyNewFile(); } else if (cmd.equals("openfile")) { File[] selectedFiles = confirmFilesToOpen(); if (selectedFiles == null) { return; } for (int i = 0; i < selectedFiles.length; i++) { this.addFile(selectedFiles[i]); } } else if (cmd.equals("savefile")) { if (fileInfors.size() == 0) { return; } if (currentFileInfor instanceof EmptyInfor) { try { saveAsFile(); } catch (IOException e) { e.printStackTrace(); } } else { try { saveFile(currentIndex); } catch (IOException e) { e.printStackTrace(); } } } else if (cmd.equals("saveasfile")) { if (fileInfors.size() == 0) { return; } try { saveAsFile(); } catch (IOException e) { e.printStackTrace(); } } else if (cmd.equals("closecurrentfile")) { if (this.checkIndex()) { closeCurrent(); } } else if (cmd.startsWith(closeFileCommandHead)) { int fileid = Integer.parseInt(cmd.substring(closeFileCommandHead .length())); closeFile(fileid); } else if (cmd.equals("closeallotherfiles")) { int thisIndex = tabbedPane.getSelectedIndex(); int deleted = 0; int deleteId = 0; while (fileInfors.size() > 1) { if (deleted == thisIndex) { deleteId = 1; } closeFile(deleteId); deleted++; } } else if (cmd.equals("closeallfiles")) { while (fileInfors.size() > 0) { closeFile(0); } currentIndex = -1; } else if (cmd.startsWith("showhistory_")) { String fileName = cmd.substring("showhistory_".length()); addFile(new File(fileName)); } // 退出 else if (cmd.equals("exitfile")) { shutdown(); } else if (cmd.equals("undoedit")) { MsgBox.msg(this, cmd); } else if (cmd.equals("redoedit")) { MsgBox.msg(this, cmd); } else if (cmd.equals("cutedit")) { MsgBox.msg(this, cmd); } else if (cmd.equals("copyedit")) { MsgBox.msg(this, cmd); } else if (cmd.equals("pasteedit")) { MsgBox.msg(this, cmd); } else if (cmd.equals("selectalledit")) { MsgBox.msg(this, cmd); } else if (cmd.equals("deselectalledit")) { MsgBox.msg(this, cmd); } else if (cmd.startsWith("setencode_")) { if (currentFileInfor instanceof EmptyInfor) { return; } if (currentFileInfor.isBinary()) { MsgBox.msg(this, "此文件是二进制文件,不能改变编码"); fixFileEncodeMenus(); return; } if (currentFileInfor.isHexMode()) { MsgBox.msg(this, "文件处于二进制编辑状态,不能改变编码"); fixFileEncodeMenus(); return; } String[] infors = cmd.split("_"); int encodeIndex = Integer.parseInt(infors[1]); // String theEncode = infors[2]; String javaEncode = Encoding.javaname[encodeIndex]; try { currentTextArea.setText(currentFileInfor.read(javaEncode)); currentTextArea.setCaretPosition(0); this.setFileEncodeMenuItem.setEnabled(true); this.defaultFileEncodeMenuItem.setEnabled(true); } catch (IOException e) { e.printStackTrace(); } } else if (cmd.equals("setfileencode")) { currentFileInfor.changeEncode(); this.setFileEncodeMenuItem.setEnabled(false); this.defaultFileEncodeMenuItem.setEnabled(false); this.currentPropertyText.setText(currentFileInfor .getPropertyString()); } else if (cmd.equals("setdefaultfileencode")) { try { currentTextArea.setText(currentFileInfor.read()); currentTextArea.setCaretPosition(0); currentPropertyText.setText(currentFileInfor .getPropertyString()); fixFileEncodeMenus(); this.setFileEncodeMenuItem.setEnabled(false); this.defaultFileEncodeMenuItem.setEnabled(false); } catch (IOException e) { e.printStackTrace(); } } else if (cmd.equals("findsearch")) { MsgBox.msg(this, cmd); } else if (cmd.equals("previoussearch")) { MsgBox.msg(this, cmd); } else if (cmd.equals("nextsearch")) { MsgBox.msg(this, cmd); } else if (cmd.equals("replacesearch")) { MsgBox.msg(this, cmd); } else if (cmd.equals("normalview")) { if (currentFileInfor instanceof EmptyInfor) { if (!currentTextArea.getText().trim().equals("")) { int ask = JOptionPane.showConfirmDialog(this, "文件 " + currentFileInfor.getName() + " 还未保存,切换显示会丢失原有数据,确定操作?"); // System.out.println(ask); // 否或取消 按纽 if (ask == 1 || ask == 2) { return; } } currentTextArea.setText(""); currentFileInfor.setHexMode(false); } else { try { String hexString = currentFileInfor.getNormalDisplay(); currentTextArea.setText(hexString); currentTextArea.setCaretPosition(0); } catch (IOException e) { e.printStackTrace(); } } } else if (cmd.equals("hexview")) { if (currentFileInfor instanceof EmptyInfor) { if (!currentTextArea.getText().trim().equals("")) { int ask = JOptionPane.showConfirmDialog(this, "文件 " + currentFileInfor.getName() + " 还未保存,显示十六进制会丢失原有数据,确定操作?"); // System.out.println(ask); // 否或取消 按纽 if (ask == 1 || ask == 2) { return; } } currentFileInfor.setHexMode(true); currentTextArea.setText(FileInfor.fillZeroForNumber(0) + FileInfor.addressSeperator); } else { try { currentTextArea.setText(currentFileInfor.getHexDisplay()); currentTextArea.setCaretPosition(0); this.repaint(); } catch (IOException e) { e.printStackTrace(); } } } // 关于 else if (cmd.equals("about")) { showAbout(); } // 未处理的命令部分.提示开发人员 else { MsgBox.alert("您还未在actionPerformed()方法中完成处理命令[" + cmd + "]的响应代码"); } } /** * @param args */ public static void main(String[] args) { String fileName = null; for (int i = 0; i < args.length; i++) { if (args[i].equals("-file")) { try { fileName = args[i + 1]; } catch (Exception e) { System.out.println("arg is missing"); } } } FileEditor shower; try { shower = new FileEditor(fileName); shower.isStandAloneProcess = true; } catch (Exception e) { e.printStackTrace(); } } }