0 Replies Latest reply: Mar 19, 2013 5:28 PM by 997387 RSS

    From jtextpane to jeditorpane

    997387
      I'd like to create a complete text editor so, i made these two code, but the first it's based on jtextpane and the second on a jeditorpane. I want to link toghether the second with the firt code , to have a cpmplete text editor. The problem is that i don't know how to do this. The fisrt think i thought to do was transform the jtext in the fisrt code in a jeditor but jeditor don't recognize the function 'append' .. Could someone help me? Thanks



      /*
      * To change this template, choose Tools | Templates
      * and open the template in the editor.
      */
      package GUI;

      import java.awt.Toolkit;
      import java.awt.datatransfer.Clipboard;
      import java.awt.datatransfer.StringSelection;
      import java.io.BufferedReader;
      import java.io.BufferedWriter;
      import java.io.File;
      import java.io.FileOutputStream;
      import java.io.FileReader;
      import java.io.IOException;
      import java.io.OutputStreamWriter;
      import javax.swing.JFileChooser;
      import javax.swing.JOptionPane;
      import javax.swing.filechooser.FileNameExtensionFilter;

      /**
      *
      * @author Elena
      */
      public class Form extends javax.swing.JFrame {

      String ClipboardData = "";
      private Object CurrentFileDirectory;
      /**
      * Creates new form Form
      */
      public Form() {
      initComponents();
      }

      /**
      * This method is called from within the constructor to initialize the form.
      * WARNING: Do NOT modify this code. The content of this method is always
      * regenerated by the Form Editor.
      */
      @SuppressWarnings("unchecked")
      // <editor-fold defaultstate="collapsed" desc="Generated Code">
      private void initComponents() {

      jScrollPane2 = new javax.swing.JScrollPane();
      editorpane = new javax.swing.JEditorPane();
      jMenuBar1 = new javax.swing.JMenuBar();
      Open = new javax.swing.JMenu();
      New = new javax.swing.JMenuItem();
      Openfile = new javax.swing.JMenuItem();
      Save = new javax.swing.JMenuItem();
      SaveAs = new javax.swing.JMenuItem();
      Exit = new javax.swing.JMenuItem();
      Cut = new javax.swing.JMenu();
      jMenuItem6 = new javax.swing.JMenuItem();
      Copy = new javax.swing.JMenuItem();
      Paste = new javax.swing.JMenuItem();
      Delete = new javax.swing.JMenuItem();
      SelectAll = new javax.swing.JMenuItem();

      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
      setTitle("Java Text Editor");

      jScrollPane2.setViewportView(editorpane);

      Open.setText("File");

      New.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
      New.setText("New");
      New.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      NewActionPerformed(evt);
      }
      });
      Open.add(New);

      Openfile.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
      Openfile.setText("Open...");
      Openfile.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      OpenfileActionPerformed(evt);
      }
      });
      Open.add(Openfile);

      Save.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
      Save.setText("Save");
      Save.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      SaveActionPerformed(evt);
      }
      });
      Open.add(Save);

      SaveAs.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
      SaveAs.setText("Save As...");
      SaveAs.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      SaveAsActionPerformed(evt);
      }
      });
      Open.add(SaveAs);

      Exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_0, java.awt.event.InputEvent.CTRL_MASK));
      Exit.setText("Exit");
      Exit.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      ExitActionPerformed(evt);
      }
      });
      Open.add(Exit);

      jMenuBar1.add(Open);

      Cut.setText("Edit");

      jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
      jMenuItem6.setText("Cut");
      jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      jMenuItem6ActionPerformed(evt);
      }
      });
      Cut.add(jMenuItem6);

      Copy.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
      Copy.setText("Copy");
      Copy.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      CopyActionPerformed(evt);
      }
      });
      Cut.add(Copy);

      Paste.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
      Paste.setText("Paste");
      Paste.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      PasteActionPerformed(evt);
      }
      });
      Cut.add(Paste);

      Delete.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DELETE, 0));
      Delete.setText("Delete");
      Delete.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      DeleteActionPerformed(evt);
      }
      });
      Cut.add(Delete);

      SelectAll.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
      SelectAll.setText("Select All");
      SelectAll.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      SelectAllActionPerformed(evt);
      }
      });
      Cut.add(SelectAll);

      jMenuBar1.add(Cut);

      setJMenuBar(jMenuBar1);

      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
      );
      layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 479, Short.MAX_VALUE)
      );

      pack();
      }// </editor-fold>

      private void NewActionPerformed(java.awt.event.ActionEvent evt) {                                   

      editorpane.setText("");

      }

      private void ExitActionPerformed(java.awt.event.ActionEvent evt) {                                    

      System.exit(0);

      }

      private void DeleteActionPerformed(java.awt.event.ActionEvent evt) {                                      

      editorpane.replaceSelection("");
      }

      private void SaveAsActionPerformed(java.awt.event.ActionEvent evt) {                                      

      JFileChooser sdChooser = new JFileChooser();
      FileNameExtensionFilter filter = new FileNameExtensionFilter("DOCX File", "txt");
      sdChooser.setFileFilter(filter);
      int returnVal = sdChooser.showSaveDialog(null);

      try{
      if(returnVal == JFileChooser.APPROVE_OPTION){
      File directory = sdChooser.getCurrentDirectory();
      String path = directory.getAbsolutePath();
      String fileName = sdChooser.getSelectedFile().getName();
      if(fileName.contains(".docx")){

      }else{
      fileName = fileName + ".docx";

      }
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "\\" + fileName)));
      bw.write(editorpane.getText());
      bw.close();
      }
      } catch(IOException e){
      JOptionPane.showMessageDialog(null, "ERROR!");
      }
      }

      private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {                                          
      ClipboardData = editorpane.getSelectedText();
      StringSelection stringSelection = new StringSelection(ClipboardData);
      Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
      clipboard.setContents(stringSelection, null);
      editorpane.replaceSelection("");

      }

      private void CopyActionPerformed(java.awt.event.ActionEvent evt) {                                    

      ClipboardData = editorpane.getSelectedText();
      StringSelection stringSelection = new StringSelection(ClipboardData);
      Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
      clipboard.setContents(stringSelection, null);


      }

      private void PasteActionPerformed(java.awt.event.ActionEvent evt) {                                     

      editorpane.append(ClipboardData);


      }

      private void SelectAllActionPerformed(java.awt.event.ActionEvent evt) {                                         

      editorpane.selectAll();

      }

      private void OpenfileActionPerformed(java.awt.event.ActionEvent evt) {                                        
      JFileChooser opChooser = new JFileChooser();
      FileNameExtensionFilter filter = new FileNameExtensionFilter("DOCX file", "docx");
      opChooser.setFileFilter(filter);
      int returnval = opChooser.showOpenDialog(null);
      File chosenFile = opChooser.getSelectedFile();

      try {

      if(returnval == JFileChooser.APPROVE_OPTION){
      BufferedReader br = new BufferedReader(new FileReader(chosenFile));
      editorpane.setText("");

      String data;
      while((data = br.readLine()) != null) {
      editorpane.append(data + "\n");}
      br.close();
      }

      }catch(IOException e){
      JOptionPane.showMessageDialog(null, "ERROR!" );
      }
      }

      private void SaveActionPerformed(java.awt.event.ActionEvent evt) {                                    

      if("".equals(CurrentFileDirectory)){


      JFileChooser sdChooser = new JFileChooser();
      FileNameExtensionFilter filter = new FileNameExtensionFilter("DOCX file", "docx");
      sdChooser.setFileFilter(filter);
      int returnval = sdChooser.showOpenDialog(null);

      try{
      if(returnval == JFileChooser.APPROVE_OPTION){
      File directory = sdChooser.getCurrentDirectory();
      String path = directory.getAbsolutePath();
      String fileName = sdChooser.getSelectedFile().getName();
      if(fileName.contains(".docx")){

      }else{
      fileName = fileName + ".docx";
      }
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "\\" + fileName)));
      bw.write(editorpane.getText());
      bw.close();}

      }catch(IOException e){     
      JOptionPane.showMessageDialog(null, "ERROR!");
      }
      }
      }

      /**
      * @param args the command line arguments
      */
      public static void main(String args[]) {
      /* Set the Nimbus look and feel */
      //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
      /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
      * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
      */
      try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
      if ("Nimbus".equals(info.getName())) {
      javax.swing.UIManager.setLookAndFeel(info.getClassName());
      break;
      }
      }
      } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      }
      //</editor-fold>

      /* Create and display the form */
      java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
      new Form().setVisible(true);
      }
      });
      }
      // Variables declaration - do not modify
      private javax.swing.JMenuItem Copy;
      private javax.swing.JMenu Cut;
      private javax.swing.JMenuItem Delete;
      private javax.swing.JMenuItem Exit;
      private javax.swing.JMenuItem New;
      private javax.swing.JMenu Open;
      private javax.swing.JMenuItem Openfile;
      private javax.swing.JMenuItem Paste;
      private javax.swing.JMenuItem Save;
      private javax.swing.JMenuItem SaveAs;
      private javax.swing.JMenuItem SelectAll;
      private javax.swing.JEditorPane editorpane;
      private javax.swing.JMenuBar jMenuBar1;
      private javax.swing.JMenuItem jMenuItem6;
      private javax.swing.JScrollPane jScrollPane2;
      // End of variables declaration
      }



      import java.awt.BorderLayout;
      import java.awt.Color;
      import java.awt.GraphicsEnvironment;
      import java.awt.GridLayout;
      import java.awt.event.ActionEvent;
      import java.awt.event.ActionListener;
      import javax.swing.Action;
      import javax.swing.JButton;
      import javax.swing.JColorChooser;
      import javax.swing.JComboBox;
      import javax.swing.JDialog;
      import javax.swing.JEditorPane;
      import javax.swing.JFrame;
      import javax.swing.JLabel;
      import javax.swing.JMenu;
      import javax.swing.JMenuBar;
      import javax.swing.JOptionPane;
      import javax.swing.JPanel;
      import javax.swing.JScrollPane;
      import javax.swing.JTextPane;
      import javax.swing.text.AttributeSet;
      import javax.swing.text.Element;
      import javax.swing.text.MutableAttributeSet;
      import javax.swing.text.SimpleAttributeSet;
      import javax.swing.text.StyleConstants;
      import javax.swing.text.StyledDocument;
      import javax.swing.text.StyledEditorKit;

      public class Colore {
      public Colore() {
      JFrame frame = new JFrame();
      JTextPane textPane = new JTextPane();
      JScrollPane scrollPane = new JScrollPane(textPane);

      JPanel north = new JPanel();

      JMenuBar menu = new JMenuBar();
      JMenu styleMenu = new JMenu();
      styleMenu.setText("Style");

      Action boldAction = new BoldAction();
      boldAction.putValue(Action.NAME, "Bold");
      styleMenu.add(boldAction);

      Action italicAction = new ItalicAction();
      italicAction.putValue(Action.NAME, "Italic");
      styleMenu.add(italicAction);

      Action foregroundAction = new ForegroundAction();
      foregroundAction.putValue(Action.NAME, "Color");
      styleMenu.add(foregroundAction);

      Action formatTextAction = new FontAndSizeAction();
      formatTextAction.putValue(Action.NAME, "Font and Size");
      styleMenu.add(formatTextAction);


      menu.add(styleMenu);

      north.add(menu);
      frame.getContentPane().setLayout(new BorderLayout());
      frame.getContentPane().add(north, BorderLayout.NORTH);
      frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
      frame.setSize(800, 500);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
      }

      public static void main(String[] args) {
      new Culo();
      }
      }
      class BoldAction extends StyledEditorKit.StyledTextAction {
      private static final long serialVersionUID = 9174670038684056758L;

      public BoldAction() {
      super("font-bold");
      }

      public String toString() {
      return "Bold";
      }

      public void actionPerformed(ActionEvent e) {
      JEditorPane editor = getEditor(e);
      if (editor != null) {
      StyledEditorKit kit = getStyledEditorKit(editor);
      MutableAttributeSet attr = kit.getInputAttributes();
      boolean bold = (StyleConstants.isBold(attr)) ? false : true;
      SimpleAttributeSet sas = new SimpleAttributeSet();
      StyleConstants.setBold(sas, bold);
      setCharacterAttributes(editor, sas, false);

      }
      }
      }

      class ItalicAction extends StyledEditorKit.StyledTextAction {

      private static final long serialVersionUID = -1428340091100055456L;

      public ItalicAction() {
      super("font-italic");
      }

      public String toString() {
      return "Italic";
      }

      public void actionPerformed(ActionEvent e) {
      JEditorPane editor = getEditor(e);
      if (editor != null) {
      StyledEditorKit kit = getStyledEditorKit(editor);
      MutableAttributeSet attr = kit.getInputAttributes();
      boolean italic = (StyleConstants.isItalic(attr)) ? false : true;
      SimpleAttributeSet sas = new SimpleAttributeSet();
      StyleConstants.setItalic(sas, italic);
      setCharacterAttributes(editor, sas, false);
      }
      }
      }
      class ForegroundAction extends StyledEditorKit.StyledTextAction {

      private static final long serialVersionUID = 6384632651737400352L;

      JColorChooser colorChooser = new JColorChooser();

      JDialog dialog = new JDialog();

      boolean noChange = false;

      boolean cancelled = false;

      public ForegroundAction() {
      super("foreground");

      }

      public void actionPerformed(ActionEvent e) {
      JTextPane editor = (JTextPane) getEditor(e);

      if (editor == null) {
      JOptionPane.showMessageDialog(null,
      "You need to select the editor pane before you can change the color.", "Error",
      JOptionPane.ERROR_MESSAGE);
      return;
      }
      int p0 = editor.getSelectionStart();
      StyledDocument doc = getStyledDocument(editor);
      Element paragraph = doc.getCharacterElement(p0);
      AttributeSet as = paragraph.getAttributes();
      fg = StyleConstants.getForeground(as);
      if (fg == null) {
      fg = Color.BLACK;
      }
      colorChooser.setColor(fg);

      JButton accept = new JButton("OK");
      accept.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
      fg = colorChooser.getColor();
      dialog.dispose();
      }
      });

      JButton cancel = new JButton("Cancel");
      cancel.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
      cancelled = true;
      dialog.dispose();
      }
      });

      JButton none = new JButton("None");
      none.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
      noChange = true;
      dialog.dispose();
      }
      });

      JPanel buttons = new JPanel();
      buttons.add(accept);
      buttons.add(none);
      buttons.add(cancel);

      dialog.getContentPane().setLayout(new BorderLayout());
      dialog.getContentPane().add(colorChooser, BorderLayout.CENTER);
      dialog.getContentPane().add(buttons, BorderLayout.SOUTH);
      dialog.setModal(true);
      dialog.pack();
      dialog.setVisible(true);

      if (!cancelled) {

      MutableAttributeSet attr = null;
      if (editor != null) {
      if (fg != null && !noChange) {
      attr = new SimpleAttributeSet();
      StyleConstants.setForeground(attr, fg);
      setCharacterAttributes(editor, attr, false);
      }
      }
      }// end if color != null
      noChange = false;
      cancelled = false;
      }

      private Color fg;
      }

      class FontAndSizeAction extends StyledEditorKit.StyledTextAction {

      private static final long serialVersionUID = 584531387732416339L;

      private String family;

      private float fontSize;

      JDialog formatText;

      private boolean accept = false;

      JComboBox fontFamilyChooser;

      JComboBox fontSizeChooser;

      public FontAndSizeAction() {
      super("Font and Size");
      }

      public String toString() {
      return "Font and Size";
      }

      public void actionPerformed(ActionEvent e) {
      JTextPane editor = (JTextPane) getEditor(e);
      int p0 = editor.getSelectionStart();
      StyledDocument doc = getStyledDocument(editor);
      Element paragraph = doc.getCharacterElement(p0);
      AttributeSet as = paragraph.getAttributes();

      family = StyleConstants.getFontFamily(as);
      fontSize = StyleConstants.getFontSize(as);

      formatText = new JDialog(new JFrame(), "Font and Size", true);
      formatText.getContentPane().setLayout(new BorderLayout());

      JPanel choosers = new JPanel();
      choosers.setLayout(new GridLayout(2, 1));

      JPanel fontFamilyPanel = new JPanel();
      fontFamilyPanel.add(new JLabel("Font"));

      GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
      String[] fontNames = ge.getAvailableFontFamilyNames();

      fontFamilyChooser = new JComboBox();
      for (int i = 0; i < fontNames.length; i++) {
      fontFamilyChooser.addItem(fontNames);
      }
      fontFamilyChooser.setSelectedItem(family);
      fontFamilyPanel.add(fontFamilyChooser);
      choosers.add(fontFamilyPanel);

      JPanel fontSizePanel = new JPanel();
      fontSizePanel.add(new JLabel("Size"));
      fontSizeChooser = new JComboBox();
      fontSizeChooser.setEditable(true);
      fontSizeChooser.addItem(new Float(4));
      fontSizeChooser.addItem(new Float(8));
      fontSizeChooser.addItem(new Float(12));
      fontSizeChooser.addItem(new Float(16));
      fontSizeChooser.addItem(new Float(20));
      fontSizeChooser.addItem(new Float(24));
      fontSizeChooser.setSelectedItem(new Float(fontSize));
      fontSizePanel.add(fontSizeChooser);
      choosers.add(fontSizePanel);

      JButton ok = new JButton("OK");
      ok.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
      accept = true;
      formatText.dispose();
      family = (String) fontFamilyChooser.getSelectedItem();
      fontSize = Float.parseFloat(fontSizeChooser.getSelectedItem().toString());
      }
      });

      JButton cancel = new JButton("Cancel");
      cancel.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
      formatText.dispose();
      }
      });

      JPanel buttons = new JPanel();
      buttons.add(ok);
      buttons.add(cancel);
      formatText.getContentPane().add(choosers, BorderLayout.CENTER);
      formatText.getContentPane().add(buttons, BorderLayout.SOUTH);
      formatText.pack();
      formatText.setVisible(true);

      MutableAttributeSet attr = null;
      if (editor != null && accept) {
      attr = new SimpleAttributeSet();
      StyleConstants.setFontFamily(attr, family);
      StyleConstants.setFontSize(attr, (int) fontSize);
      setCharacterAttributes(editor, attr, false);
      }

      }
      }