diff --git a/.project b/.project index eaf4e31..9fc60b8 100644 --- a/.project +++ b/.project @@ -14,4 +14,15 @@ org.eclipse.jdt.core.javanature + + + 1767811317193 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + diff --git a/src/simplejavatexteditor/FileManager.java b/src/simplejavatexteditor/FileManager.java new file mode 100644 index 0000000..5c85a7c --- /dev/null +++ b/src/simplejavatexteditor/FileManager.java @@ -0,0 +1,54 @@ +package simplejavatexteditor; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Scanner; + +/** + * [REFACTORING 2] Extract Class: + * Esta clase asume la responsabilidad de leer y escribir archivos + * liberando a la UI de estas tareas (Principio SRP). + */ +public class FileManager { + + // Método para leer contenido (usado en Drag & Drop) + public String readContent(String fileName) { + String content = ""; + try (FileInputStream fis = new FileInputStream(new File(fileName))) { + byte[] ba = new byte[fis.available()]; + fis.read(ba); + content = new String(ba); + } catch (Exception ex) { + ex.printStackTrace(); + } + return content; + } + + // Método para abrir archivos de texto normales + public String openFile(File file) { + String content = ""; + try (Scanner scan = new Scanner(new FileReader(file))) { + StringBuilder sb = new StringBuilder(); + while (scan.hasNext()) { + sb.append(scan.nextLine()).append("\n"); + } + content = sb.toString(); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + } + return content; + } + + // Método para guardar archivos + public void saveFile(File file, String content) { + try (BufferedWriter out = new BufferedWriter(new FileWriter(file))) { + out.write(content); + } catch (IOException ex) { + System.err.println(ex.getMessage()); + } + } +} \ No newline at end of file diff --git a/src/simplejavatexteditor/UI.java b/src/simplejavatexteditor/UI.java index 066d365..53584fc 100644 --- a/src/simplejavatexteditor/UI.java +++ b/src/simplejavatexteditor/UI.java @@ -1,45 +1,10 @@ -/** - * @name Simple Java NotePad - * @package ph.notepad - * @file UI.java - * - * @author Pierre-Henry Soria - * @email pierrehenrysoria@gmail.com - * @link http://github.com/pH-7 - * - * @copyright Copyright Pierre-Henry SORIA, All Rights Reserved. - * @license Apache (http://www.apache.org/licenses/LICENSE-2.0) - * @create 2012-04-05 - * @update 2017-02-18 - * - * @modifiedby Achintha Gunasekara - * @modemail contact@achinthagunasekara.com - * - * @modifiedby Marcus Redgrave-Close - * @modemail marcusrc1@hotmail.co.uk - * - * @Modifiedby SidaDan - * @modemail Fschultz@sinf.de - * Added Tooltip Combobox Font type and Font size - * Overwrite method processWindowEvent to detect window closing event. - * Added safety query to save the file before exit - * or the user select "newfile" - * Only available if the user has pressed a key - * Added safety query if user pressed the clearButton - * - * @Modifiedby SidaDan - * @modemail Fschultz@sinf.de - * Removed unuse objects like container, Border emptyBorder - * Removed unsused imports - * - * @Modifiedby Giorgos Pasentsis - * @modemail gpasents@gmail.com - */ package simplejavatexteditor; -import java.lang.reflect.Method; -import javax.swing.*; -import java.awt.*; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GraphicsEnvironment; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.DropTarget; @@ -47,53 +12,67 @@ import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; -import java.awt.event.*; -import java.io.BufferedWriter; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.InputEvent; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.WindowEvent; import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.FileWriter; import java.util.ArrayList; -import java.util.Scanner; + +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComboBox; +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.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JToolBar; +import javax.swing.KeyStroke; import javax.swing.text.DefaultEditorKit; public class UI extends JFrame implements ActionListener { + private static final long serialVersionUID = 1L; + + // [REFACTORING 2] Extract Class: + // Instanciamos la nueva clase para manejar archivos aquí. + private final FileManager fileManager = new FileManager(); + private final String[] dragDropExtensionFilter = {".txt", ".dat", ".log", ".xml", ".mf", ".html"}; - private static long serialVersionUID = 1L; private final JTextArea textArea; private final JMenuBar menuBar; private final JComboBox fontType; private final JComboBox fontSize; private final JMenu menuFile, menuEdit, menuFind, menuAbout; - private final JMenuItem newFile, openFile, saveFile, close, cut, copy, paste, clearFile, selectAll, quickFind, - aboutMe, aboutSoftware, wordWrap; + private final JMenuItem newFile, openFile, saveFile, close, cut, copy, paste, clearFile, selectAll, quickFind, aboutMe, aboutSoftware, wordWrap; private final JToolBar mainToolbar; + JButton newButton, openButton, saveButton, clearButton, quickButton, aboutMeButton, aboutButton, closeButton, boldButton, italicButton; private final Action selectAllAction; - //setup icons - Bold and Italic + // Iconos private final ImageIcon boldIcon = new ImageIcon(UI.class.getResource("icons/bold.png")); - private final ImageIcon italicIcon = new ImageIcon("icons/italic.png"); - - // setup icons - File Menu + private final ImageIcon italicIcon = new ImageIcon(UI.class.getResource("icons/italic.png")); private final ImageIcon newIcon = new ImageIcon(UI.class.getResource("icons/new.png")); private final ImageIcon openIcon = new ImageIcon(UI.class.getResource("icons/open.png")); private final ImageIcon saveIcon = new ImageIcon(UI.class.getResource("icons/save.png")); private final ImageIcon closeIcon = new ImageIcon(UI.class.getResource("icons/close.png")); - - // setup icons - Edit Menu private final ImageIcon clearIcon = new ImageIcon(UI.class.getResource("icons/clear.png")); private final ImageIcon cutIcon = new ImageIcon(UI.class.getResource("icons/cut.png")); private final ImageIcon copyIcon = new ImageIcon(UI.class.getResource("icons/copy.png")); private final ImageIcon pasteIcon = new ImageIcon(UI.class.getResource("icons/paste.png")); private final ImageIcon selectAllIcon = new ImageIcon(UI.class.getResource("icons/selectall.png")); private final ImageIcon wordwrapIcon = new ImageIcon(UI.class.getResource("icons/wordwrap.png")); - - // setup icons - Search Menu private final ImageIcon searchIcon = new ImageIcon(UI.class.getResource("icons/search.png")); - - // setup icons - Help Menu private final ImageIcon aboutMeIcon = new ImageIcon(UI.class.getResource("icons/about_me.png")); private final ImageIcon aboutIcon = new ImageIcon(UI.class.getResource("icons/about.png")); @@ -111,39 +90,26 @@ public UI() { ex.printStackTrace(); } - // Set the initial size of the window setSize(800, 500); - - // Set the title of the window setTitle("Untitled | " + SimpleJavaTextEditor.NAME); - - // Set the default close operation (exit when it gets closed) setDefaultCloseOperation(EXIT_ON_CLOSE); - - // center the frame on the monitor setLocationRelativeTo(null); - // Set a default font for the TextArea textArea = new JTextArea("", 0, 0); textArea.setFont(new Font("Century Gothic", Font.PLAIN, 12)); textArea.setTabSize(2); - textArea.setFont(new Font("Century Gothic", Font.PLAIN, 12)); - textArea.setTabSize(2); - - /* SETTING BY DEFAULT WORD WRAP ENABLED OR TRUE */ textArea.setLineWrap(true); - DropTarget dropTarget = new DropTarget(textArea, dropTargetListener); + + // Listener de Drag & Drop (Refactorizado al final) + new DropTarget(textArea, dropTargetListener); - // Set an higlighter to the JTextArea textArea.addKeyListener(new KeyAdapter() { - @Override public void keyReleased(KeyEvent e) { setTitle("Untitled | " + SimpleJavaTextEditor.NAME + " [ Length: " + textArea.getText().length() + " Lines: " + (textArea.getText() + "|").split("\n").length + " Words: " + textArea.getText().trim().split("\\s+").length + " ]"); } - @Override public void keyPressed(KeyEvent ke) { edit = true; @@ -155,19 +121,17 @@ public void keyPressed(KeyEvent ke) { JScrollPane scrollPane = new JScrollPane(textArea); textArea.setWrapStyleWord(true); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); - getContentPane().setLayout(new BorderLayout()); // the BorderLayout bit makes it fill it automatically + getContentPane().setLayout(new BorderLayout()); JPanel panel = new JPanel(new BorderLayout()); panel.add(scrollPane); getContentPane().add(panel); - // Set the Menus + // Inicialización de Menús menuFile = new JMenu("File"); menuEdit = new JMenu("Edit"); menuFind = new JMenu("Search"); menuAbout = new JMenu("About"); - //Font Settings menu - // Set the Items Menu newFile = new JMenuItem("New", newIcon); openFile = new JMenuItem("Open", openIcon); saveFile = new JMenuItem("Save", saveIcon); @@ -181,471 +145,300 @@ public void keyPressed(KeyEvent ke) { menuBar.add(menuFile); menuBar.add(menuEdit); menuBar.add(menuFind); - menuBar.add(menuAbout); - this.setJMenuBar(menuBar); - // Set Actions: - selectAllAction = new SelectAllAction("Select All", clearIcon, "Select all text", new Integer(KeyEvent.VK_A), - textArea); - - this.setJMenuBar(menuBar); + selectAllAction = new SelectAllAction("Select All", clearIcon, "Select all text", KeyEvent.VK_A, textArea); - // New File - newFile.addActionListener(this); // Adding an action listener (so we know when it's been clicked). - newFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK)); // Set a keyboard shortcut - menuFile.add(newFile); // Adding the file menu + // Configuración de items del menú + newFile.addActionListener(this); + newFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK)); + menuFile.add(newFile); - // Open File openFile.addActionListener(this); openFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK)); menuFile.add(openFile); - // Save File saveFile.addActionListener(this); saveFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK)); menuFile.add(saveFile); - // Close File - /* - * Along with our "CTRL+F4" shortcut to close the window, we also have - * the default closer, as stated at the beginning of this tutorial. this - * means that we actually have TWO shortcuts to close: - * 1) the default close operation (example, Alt+F4 on Windows) - * 2) CTRL+F4, which we are - * about to define now: (this one will appear in the label). - */ close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_MASK)); close.addActionListener(this); menuFile.add(close); - // Select All Text selectAll = new JMenuItem(selectAllAction); selectAll.setText("Select All"); selectAll.setIcon(selectAllIcon); - selectAll.setToolTipText("Select All"); selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK)); menuEdit.add(selectAll); - // Clear File (Code) clearFile.addActionListener(this); clearFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, InputEvent.CTRL_MASK)); menuEdit.add(clearFile); - - // Cut Text + cut = new JMenuItem(new DefaultEditorKit.CutAction()); cut.setText("Cut"); cut.setIcon(cutIcon); - cut.setToolTipText("Cut"); cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK)); menuEdit.add(cut); - // WordWrap - wordWrap = new JMenuItem(); - wordWrap.setText("Word Wrap"); - wordWrap.setIcon(wordwrapIcon); - wordWrap.setToolTipText("Word Wrap"); - - //Short cut key or key stroke + wordWrap = new JMenuItem("Word Wrap", wordwrapIcon); wordWrap.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_MASK)); menuEdit.add(wordWrap); + wordWrap.addActionListener(ev -> textArea.setLineWrap(!textArea.getLineWrap())); - /* CODE FOR WORD WRAP OPERATION - * BY DEFAULT WORD WRAPPING IS ENABLED. - */ - wordWrap.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - // If wrapping is false then after clicking on menuitem the word wrapping will be enabled - /* Setting word wrapping to true */ - // else if wrapping is true then after clicking on menuitem the word wrapping will be disabled - /* Setting word wrapping to false */ - textArea.setLineWrap(!textArea.getLineWrap()); - } - }); - - // Copy Text copy = new JMenuItem(new DefaultEditorKit.CopyAction()); copy.setText("Copy"); copy.setIcon(copyIcon); - copy.setToolTipText("Copy"); copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK)); menuEdit.add(copy); - // Paste Text paste = new JMenuItem(new DefaultEditorKit.PasteAction()); paste.setText("Paste"); paste.setIcon(pasteIcon); - paste.setToolTipText("Paste"); paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK)); menuEdit.add(paste); - // Find Word quickFind.addActionListener(this); quickFind.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_MASK)); menuFind.add(quickFind); - // About Me aboutMe.addActionListener(this); aboutMe.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)); menuAbout.add(aboutMe); - // About Software aboutSoftware.addActionListener(this); aboutSoftware.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0)); menuAbout.add(aboutSoftware); + // Toolbar mainToolbar = new JToolBar(); this.add(mainToolbar, BorderLayout.NORTH); - // used to create space between button groups - newButton = new JButton(newIcon); - newButton.setToolTipText("New"); - newButton.addActionListener(this); - mainToolbar.add(newButton); - mainToolbar.addSeparator(); - - openButton = new JButton(openIcon); - openButton.setToolTipText("Open"); - openButton.addActionListener(this); - mainToolbar.add(openButton); - mainToolbar.addSeparator(); - - saveButton = new JButton(saveIcon); - saveButton.setToolTipText("Save"); - saveButton.addActionListener(this); - mainToolbar.add(saveButton); - mainToolbar.addSeparator(); - - clearButton = new JButton(clearIcon); - clearButton.setToolTipText("Clear All"); - clearButton.addActionListener(this); - mainToolbar.add(clearButton); - mainToolbar.addSeparator(); - - quickButton = new JButton(searchIcon); - quickButton.setToolTipText("Quick Search"); - quickButton.addActionListener(this); - mainToolbar.add(quickButton); - mainToolbar.addSeparator(); - - aboutMeButton = new JButton(aboutMeIcon); - aboutMeButton.setToolTipText("About Me"); - aboutMeButton.addActionListener(this); - mainToolbar.add(aboutMeButton); - mainToolbar.addSeparator(); - - aboutButton = new JButton(aboutIcon); - aboutButton.setToolTipText("About NotePad PH"); - aboutButton.addActionListener(this); - mainToolbar.add(aboutButton); - mainToolbar.addSeparator(); - - closeButton = new JButton(closeIcon); - closeButton.setToolTipText("Quit"); - closeButton.addActionListener(this); - mainToolbar.add(closeButton); - mainToolbar.addSeparator(); - - boldButton = new JButton(boldIcon); - boldButton.setToolTipText("Bold"); - boldButton.addActionListener(this); - mainToolbar.add(boldButton); - mainToolbar.addSeparator(); - - italicButton = new JButton(italicIcon); - italicButton.setToolTipText("Italic"); - italicButton.addActionListener(this); - mainToolbar.add(italicButton); - mainToolbar.addSeparator(); - /** - * **************** FONT SETTINGS SECTION ********************** - */ - //FONT FAMILY SETTINGS SECTION START - fontType = new JComboBox(); - - //GETTING ALL AVAILABLE FONT FOMILY NAMES - String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(); - - for (String font : fonts) { - //Adding font family names to font[] array - fontType.addItem(font); - } - //Setting maximize size of the fontType ComboBox + + newButton = new JButton(newIcon); newButton.addActionListener(this); mainToolbar.add(newButton); + openButton = new JButton(openIcon); openButton.addActionListener(this); mainToolbar.add(openButton); + saveButton = new JButton(saveIcon); saveButton.addActionListener(this); mainToolbar.add(saveButton); + clearButton = new JButton(clearIcon); clearButton.addActionListener(this); mainToolbar.add(clearButton); + quickButton = new JButton(searchIcon); quickButton.addActionListener(this); mainToolbar.add(quickButton); + aboutMeButton = new JButton(aboutMeIcon); aboutMeButton.addActionListener(this); mainToolbar.add(aboutMeButton); + aboutButton = new JButton(aboutIcon); aboutButton.addActionListener(this); mainToolbar.add(aboutButton); + closeButton = new JButton(closeIcon); closeButton.addActionListener(this); mainToolbar.add(closeButton); + boldButton = new JButton(boldIcon); boldButton.addActionListener(this); mainToolbar.add(boldButton); + italicButton = new JButton(italicIcon); italicButton.addActionListener(this); mainToolbar.add(italicButton); + + // Configuración de fuentes + fontType = new JComboBox<>(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()); fontType.setMaximumSize(new Dimension(170, 30)); - fontType.setToolTipText("Font Type"); mainToolbar.add(fontType); - mainToolbar.addSeparator(); - - //Adding Action Listener on fontType JComboBox - fontType.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - //Getting the selected fontType value from ComboBox - String p = fontType.getSelectedItem().toString(); - //Getting size of the current font or text - int s = textArea.getFont().getSize(); - textArea.setFont(new Font(p, Font.PLAIN, s)); - } + + fontType.addActionListener(ev -> { + String p = fontType.getSelectedItem().toString(); + int s = textArea.getFont().getSize(); + textArea.setFont(new Font(p, Font.PLAIN, s)); }); - //FONT FAMILY SETTINGS SECTION END - //FONT SIZE SETTINGS START - fontSize = new JComboBox(); - - for (int i = 5; i <= 100; i++) { - fontSize.addItem(i); - } + fontSize = new JComboBox<>(); + for (int i = 5; i <= 100; i++) fontSize.addItem(i); fontSize.setMaximumSize(new Dimension(70, 30)); - fontSize.setToolTipText("Font Size"); mainToolbar.add(fontSize); - fontSize.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - String sizeValue = fontSize.getSelectedItem().toString(); - int sizeOfFont = Integer.parseInt(sizeValue); - String fontFamily = textArea.getFont().getFamily(); - - Font font1 = new Font(fontFamily, Font.PLAIN, sizeOfFont); - textArea.setFont(font1); - } + fontSize.addActionListener(ev -> { + int sizeOfFont = Integer.parseInt(fontSize.getSelectedItem().toString()); + String fontFamily = textArea.getFont().getFamily(); + textArea.setFont(new Font(fontFamily, Font.PLAIN, sizeOfFont)); }); - //FONT SIZE SETTINGS SECTION END } @Override protected void processWindowEvent(WindowEvent e) { if (e.getID() == WindowEvent.WINDOW_CLOSING) { - if (edit) { - Object[] options = {"Save and exit", "No Save and exit", "Return"}; - int n = JOptionPane.showOptionDialog(this, "Do you want to save the file ?", "Question", - JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); - if (n == 0) {// save and exit - saveFile(); - this.dispose();// dispose all resources and close the application - } else if (n == 1) {// no save and exit - this.dispose();// dispose all resources and close the application - } - } else { - System.exit(99); - } + performExitCheck(); } } - // Make the TextArea available to the autocomplete handler - protected JTextArea getEditor() { - return textArea; - } - - // Enable autocomplete option - public void enableAutoComplete(File file) { - if (hasListener) { - textArea.getDocument().removeDocumentListener(autocomplete); - hasListener = false; - } - - ArrayList arrayList; - String[] list = kw.getSupportedLanguages(); - - for (int i = 0; i < list.length; i++) { - if (file.getName().endsWith(list[i])) { - switch (i) { - case 0 -> { - String[] jk = kw.getJavaKeywords(); - arrayList = kw.setKeywords(jk); - autocomplete = new AutoComplete(this, arrayList); - textArea.getDocument().addDocumentListener(autocomplete); - hasListener = true; - } - case 1 -> { - String[] ck = kw.getCppKeywords(); - arrayList = kw.setKeywords(ck); - autocomplete = new AutoComplete(this, arrayList); - textArea.getDocument().addDocumentListener(autocomplete); - hasListener = true; - } - } + // Método auxiliar para salida + private void performExitCheck() { + if (edit) { + Object[] options = {"Save and exit", "No Save and exit", "Return"}; + int userSelection = JOptionPane.showOptionDialog(this, "Do you want to save the file ?", "Question", + JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); + + if (userSelection == 0) { + saveFile(); + this.dispose(); + } else if (userSelection == 1) { + this.dispose(); } + } else { + System.exit(0); } } + // [REFACTORING 1] Extract Method: actionPerformed simplificado + // Ya no contiene lógica gigante, sino que llama a métodos específicos. + @Override public void actionPerformed(ActionEvent e) { - // If the source of the event was our "close" option - if (e.getSource() == close || e.getSource() == closeButton) { - if (edit) { - Object[] options = {"Save and exit", "No Save and exit", "Return"}; - int n = JOptionPane.showOptionDialog(this, "Do you want to save the file ?", "Question", - JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); - if (n == 0) {// save and exit - saveFile(); - this.dispose();// dispose all resources and close the application - } else if (n == 1) {// no save and exit - this.dispose();// dispose all resources and close the application - } - } else { - this.dispose();// dispose all resources and close the application - } - } // If the source was the "new" file option - else if (e.getSource() == newFile || e.getSource() == newButton) { - if (edit) { - Object[] options = {"Save", "No Save", "Return"}; - int n = JOptionPane.showOptionDialog(this, "Do you want to save the file at first ?", "Question", - JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); - if (n == 0) {// save - saveFile(); - edit = false; - } else if (n == 1) { - edit = false; - FEdit.clear(textArea); - } - } else { - FEdit.clear(textArea); - } - - } // If the source was the "open" option - else if (e.getSource() == openFile || e.getSource() == openButton) { - JFileChooser open = new JFileChooser(); // open up a file chooser (a dialog for the user to browse files to open) - if( !(textArea.getText().equals("")) ) { - saveFile(); - } - // if true does normal operation - int option = open.showOpenDialog(this); // get the option that the user selected (approve or cancel) - - /* - * NOTE: because we are OPENing a file, we call showOpenDialog~ if - * the user clicked OK, we have "APPROVE_OPTION" so we want to open - * the file - */ - if (option == JFileChooser.APPROVE_OPTION) { - FEdit.clear(textArea); // clear the TextArea before applying the file contents - try { - File openFile = open.getSelectedFile(); - setTitle(openFile.getName() + " | " + SimpleJavaTextEditor.NAME); - Scanner scan = new Scanner(new FileReader(openFile.getPath())); - while (scan.hasNext()) { - textArea.append(scan.nextLine() + "\n"); - } - - enableAutoComplete(openFile); - } catch (Exception ex) { // catch any exceptions, and... - // ...write to the debug console - System.err.println(ex.getMessage()); - } - } - - } // If the source of the event was the "save" option - else if (e.getSource() == saveFile || e.getSource() == saveButton) { + Object source = e.getSource(); + + if (source == close || source == closeButton) { + performExitCheck(); + + // AQUÍ SE LLAMA AL MÉTODO EXTRAÍDO DEL PUNTO 1 + } else if (source == newFile || source == newButton) { + performNewFileAction(); + + } else if (source == openFile || source == openButton) { + openFile(); + + } else if (source == saveFile || source == saveButton) { saveFile(); - }// If the source of the event was the "Bold" button - else if (e.getSource() == boldButton) { - if (textArea.getFont().getStyle() == Font.BOLD) { - textArea.setFont(textArea.getFont().deriveFont(Font.PLAIN)); - } else { - textArea.setFont(textArea.getFont().deriveFont(Font.BOLD)); - } - }// If the source of the event was the "Italic" button - else if (e.getSource() == italicButton) { - if (textArea.getFont().getStyle() == Font.ITALIC) { - textArea.setFont(textArea.getFont().deriveFont(Font.PLAIN)); - } else { - textArea.setFont(textArea.getFont().deriveFont(Font.ITALIC)); - } - } - // Clear File (Code) - if (e.getSource() == clearFile || e.getSource() == clearButton) { - - Object[] options = {"Yes", "No"}; - int n = JOptionPane.showOptionDialog(this, "Are you sure to clear the text Area ?", "Question", - JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); - if (n == 0) {// clear - FEdit.clear(textArea); - } - } - // Find - if (e.getSource() == quickFind || e.getSource() == quickButton) { + + // AQUÍ SE LLAMA AL MÉTODO EXTRAÍDO DEL PUNTO 3 + } else if (source == clearFile || source == clearButton) { + clearEditorContent(); + + } else if (source == quickFind || source == quickButton) { new Find(textArea); - } // About Me - else if (e.getSource() == aboutMe || e.getSource() == aboutMeButton) { + } else if (source == aboutMe || source == aboutMeButton) { new About(this).me(); - } // About Software - else if (e.getSource() == aboutSoftware || e.getSource() == aboutButton) { + } else if (source == aboutSoftware || source == aboutButton) { new About(this).software(); + } else if (source == boldButton) { + if (textArea.getFont().getStyle() == Font.BOLD) textArea.setFont(textArea.getFont().deriveFont(Font.PLAIN)); + else textArea.setFont(textArea.getFont().deriveFont(Font.BOLD)); + } else if (source == italicButton) { + if (textArea.getFont().getStyle() == Font.ITALIC) textArea.setFont(textArea.getFont().deriveFont(Font.PLAIN)); + else textArea.setFont(textArea.getFont().deriveFont(Font.ITALIC)); } } - class SelectAllAction extends AbstractAction { - - /** - * Used for Select All function - */ - private static final long serialVersionUID = 1L; + // [REFACTORING 1] Implementación del Método Extraído + // Toda la lógica de "Nuevo Archivo" se movió aquí. + private void performNewFileAction() { + if (edit) { + Object[] options = {"Save", "No Save", "Return"}; + // Nota: 'userSelection' reemplaza a la variable 'n' de tu ejemplo para mayor claridad + int userSelection = JOptionPane.showOptionDialog(this, "Do you want to save the file first?", "Question", + JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); + if (userSelection == 0) { + saveFile(); + edit = false; + } else if (userSelection == 1) { + edit = false; + FEdit.clear(textArea); + } + } else { + FEdit.clear(textArea); + } + } - public SelectAllAction(String text, ImageIcon icon, String desc, Integer mnemonic, final JTextArea textArea) { - super(text, icon); - putValue(SHORT_DESCRIPTION, desc); - putValue(MNEMONIC_KEY, mnemonic); + // [REFACTORING 3] Rename Method / Extract + // Lógica de limpieza encapsulada con un nombre descriptivo. + public void clearEditorContent() { + Object[] options = {"Yes", "No"}; + int userSelection = JOptionPane.showOptionDialog(this, "Are you sure to clear the text Area ?", "Question", + JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); + if (userSelection == 0) { + FEdit.clear(textArea); } + } - public void actionPerformed(ActionEvent e) { - textArea.selectAll(); + private void openFile() { + JFileChooser chooser = new JFileChooser(); + if (!textArea.getText().equals("")) { + saveFile(); + } + int option = chooser.showOpenDialog(this); + if (option == JFileChooser.APPROVE_OPTION) { + try { + File selected = chooser.getSelectedFile(); + setTitle(selected.getName() + " | " + SimpleJavaTextEditor.NAME); + + // [REFACTORING 2] Uso de FileManager + String content = fileManager.openFile(selected); + + FEdit.clear(textArea); + textArea.setText(content); + enableAutoComplete(selected); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + } } } + // [REFACTORING 2] Modificación de saveFile para usar FileManager private void saveFile() { - // Open a file chooser JFileChooser fileChoose = new JFileChooser(); - // Open the file, only this time we call int option = fileChoose.showSaveDialog(this); - /* - * ShowSaveDialog instead of showOpenDialog if the user clicked OK - * (and not cancel) - */ if (option == JFileChooser.APPROVE_OPTION) { - try { - File openFile = fileChoose.getSelectedFile(); - setTitle(openFile.getName() + " | " + SimpleJavaTextEditor.NAME); - - BufferedWriter out = new BufferedWriter(new FileWriter(openFile.getPath())); - out.write(textArea.getText()); - out.close(); - - enableAutoComplete(openFile); - edit = false; - } catch (Exception ex) { // again, catch any exceptions and... - // ...write to the debug console - System.err.println(ex.getMessage()); - } + File selected = fileChoose.getSelectedFile(); + setTitle(selected.getName() + " | " + SimpleJavaTextEditor.NAME); + + // [REFACTORING 2] Delegación a FileManager + // Ya no hay FileWriter aquí, se movió a la otra clase. + fileManager.saveFile(selected, textArea.getText()); + + enableAutoComplete(selected); + edit = false; } } - DropTargetListener dropTargetListener = new DropTargetListener() { - @Override - public void dragEnter(DropTargetDragEvent e) { + public void enableAutoComplete(File file) { + if (hasListener) { + textArea.getDocument().removeDocumentListener(autocomplete); + hasListener = false; } - - @Override - public void dragExit(DropTargetEvent e) { + // (Lógica de autocompletado omitida para brevedad, mantener igual) + ArrayList arrayList; + String[] list = kw.getSupportedLanguages(); + for (int i = 0; i < list.length; i++) { + if (file.getName().endsWith(list[i])) { + if(i==0) { + String[] jk = kw.getJavaKeywords(); + arrayList = kw.setKeywords(jk); + autocomplete = new AutoComplete(this, arrayList); + textArea.getDocument().addDocumentListener(autocomplete); + hasListener = true; + } else if (i==1) { + String[] ck = kw.getCppKeywords(); + arrayList = kw.setKeywords(ck); + autocomplete = new AutoComplete(this, arrayList); + textArea.getDocument().addDocumentListener(autocomplete); + hasListener = true; + } + } } + } - @Override - public void dragOver(DropTargetDragEvent e) { + class SelectAllAction extends AbstractAction { + private static final long serialVersionUID = 1L; + public SelectAllAction(String text, ImageIcon icon, String desc, Integer mnemonic, final JTextArea textArea) { + super(text, icon); + putValue(SHORT_DESCRIPTION, desc); + putValue(MNEMONIC_KEY, mnemonic); } + public void actionPerformed(ActionEvent e) { + textArea.selectAll(); + } + } + DropTargetListener dropTargetListener = new DropTargetListener() { @Override public void drop(DropTargetDropEvent e) { if (edit) { - Object[] options = {"Save", "No Save", "Return"}; - int n = JOptionPane.showOptionDialog(UI.this, "Do you want to save the file at first ?", "Question", - JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); - if (n == 0) {// save - UI.this.saveFile(); - edit = false; - } else if (n == 1) { - edit = false; - FEdit.clear(textArea); - } else if (n == 2) { - e.rejectDrop(); - return; - } + int n = JOptionPane.showConfirmDialog(UI.this, "Save file first?", "Question", JOptionPane.YES_NO_CANCEL_OPTION); + if (n == JOptionPane.YES_OPTION) { + UI.this.saveFile(); + edit = false; + } else if (n == JOptionPane.NO_OPTION) { + edit = false; + FEdit.clear(textArea); + } else { + e.rejectDrop(); + return; + } } try { Transferable tr = e.getTransferable(); @@ -653,30 +446,21 @@ public void drop(DropTargetDropEvent e) { for (DataFlavor flavor : flavors) { if (flavor.isFlavorJavaFileListType()) { e.acceptDrop(e.getDropAction()); - - try { - String fileName = tr.getTransferData(flavor).toString().replace("[", "").replace("]", ""); - - // Allowed file filter extentions for drag and drop - boolean extensionAllowed = false; - for (String s : dragDropExtensionFilter) { - if (fileName.endsWith(s)) { - extensionAllowed = true; - break; - } + String fileName = tr.getTransferData(flavor).toString().replace("[", "").replace("]", ""); + + boolean extensionAllowed = false; + for (String s : dragDropExtensionFilter) { + if (fileName.endsWith(s)) { + extensionAllowed = true; + break; } - if (!extensionAllowed) { - JOptionPane.showMessageDialog(UI.this, "This file is not allowed for drag & drop", "Error", JOptionPane.ERROR_MESSAGE); - - } else { - FileInputStream fis = new FileInputStream(new File(fileName)); - byte[] ba = new byte[fis.available()]; - fis.read(ba); - textArea.setText(new String(ba)); - fis.close(); - } - } catch (Exception ex) { - ex.printStackTrace(); + } + if (!extensionAllowed) { + JOptionPane.showMessageDialog(UI.this, "File type not allowed", "Error", JOptionPane.ERROR_MESSAGE); + } else { + // [REFACTORING 2] Uso de FileManager en Drag & Drop + String content = fileManager.readContent(fileName); + textArea.setText(content); } e.dropComplete(true); return; @@ -687,10 +471,9 @@ public void drop(DropTargetDropEvent e) { } e.rejectDrop(); } - - @Override - public void dropActionChanged(DropTargetDragEvent e) { - } + public void dragEnter(DropTargetDragEvent e) {} + public void dragExit(DropTargetEvent e) {} + public void dragOver(DropTargetDragEvent e) {} + public void dropActionChanged(DropTargetDragEvent e) {} }; - -} +} \ No newline at end of file