elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Rompecabezas de Bitcoin, Medio millón USD en premios


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  Editor texto multitab
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Editor texto multitab  (Leído 1,434 veces)
stympy

Desconectado Desconectado

Mensajes: 12


Ver Perfil
Editor texto multitab
« en: 17 Septiembre 2013, 20:46 pm »

Muy buen dia a todos , hace mucho que no entraba al foro. He estado revisando viejas practicas en java y queria modificar un editor de texto que tenia hecho ya hace algo de tiempo, el editor trabaja bien tiene las funciones basicas, cortar, pegar , insertar etc. menu popup con el raton etc

Pero ahora quiero hacerlo multitab, encontre un ejempo en la red http://paperjammed.com/2012/11/22/adding-tab-close-buttons-to-a-jtabbedpane-in-java-swing/ , pero le quiero agregar las funciones de mi antiguo editor de texto a cada tab se le asigna un "undomanager", funcines de un editor "cortar, pegar, copiar,ect...", y el despligue del menu popup con el raton.

ahora bien lo anterior es para cada tab y no me da problemas he modificado en codigo y me queda:


Ahora bien se supone que hay un boton para undo y otro para redo

Citar
   
JToolBar toolBar = new JToolBar();
toolBar.setBounds(0, 0, 648, 20);
toolBar.setFloatable(false);

TemplatesP.add(toolBar, BorderLayout.PAGE_START);

JButton newtab,cutButtontm, copyButtontm, pasteButtontm,saveButtontm,loadButtontemp,BuscarButtemp;


          toolBar.add(newtab = new JButton(""));
          newtab.setBounds(306, 340, 22, 22);
            //textNotes.add(cutButton = new JButton("tab"));
          newtab.setIcon(new ImageIcon(".\\icons\\Cut-icon.png"));
          newtab.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                   System.out.println("Add new tab!");
                    tabCount++;
                    
                    JTextArea nueva =  new JTextArea("hola");
                    
                    
                    JScrollPane scrollPane = new JScrollPane(nueva);
                    Icon icon = PAGE_ICON;
                    addClosableTab(tabbedPane, scrollPane, "Tab " + tabCount, icon,nueva); // aqui se crea una nueva tab
                    
                    
               }
             });
      
      

       toolBar.add(cutButtontm = new JButton(""));
        cutButtontm.setBounds(306, 340, 22, 22);
         //textNotes.add(cutButton = new JButton("Cut"));
        cutButtontm.setIcon(new ImageIcon(".\\icons\\Cut-icon.png"));
        cutButtontm.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e) {
               TemTextArea.cut();
               updatebuttoms();
               TemTextArea.requestFocus();
               
               
               e.getActionCommand();
               
               System.out.println(e.toString());
               System.out.println(e.getActionCommand()); ///aqui pretendo enviar evento a todos los componentes
            }
          });
        
   cutButtontm.setActionCommand("CORTAR");  



Citar
   public static void addClosableTab(final JTabbedPane tabbedPane, final JScrollPane c, final String title,final Icon icon, final JTextArea e) {
           // Add the tab to the pane without any label
           tabbedPane.addTab(null, c);
           int pos = tabbedPane.indexOfComponent(c);
           
          final Icon CLOSE_TAB_ICON = new ImageIcon(".\\icons\\Delete-icon.png");
          final Icon PAGE_ICON = new ImageIcon(".\\icons\\Copy-icon.png");
          
   
        System.out.println(tabbedPane.indexOfComponent(c));
          System.out.println( c.getComponents());
        
        JViewport viewport = c.getViewport();
        Component[] components = viewport.getComponents();
         System.out.println( components[0]);
   ///agregar evento
         components[0].setVisible(true);
        //components[0].handleEvent(evt)
        //components[0].action(evt, what)
        
         //components[0].gett
        
        
        Preparejtex(e); ///agregar eventos y menos al jtxtarea para cada tab
        
           // Create a FlowLayout that will space things 5px apart
           FlowLayout f = new FlowLayout(FlowLayout.CENTER, 5, 0);

           // Make a small JPanel with the layout and make it non-opaque
           JPanel pnlTab = new JPanel(f);
           pnlTab.setOpaque(false);

           // Add a JLabel with title and the left-side tab icon
           JLabel lblTitle = new JLabel(title);
           lblTitle.setIcon(icon);

           // Create a JButton for the close tab button
           JButton btnClose = new JButton();
           btnClose.setOpaque(false);

           // Configure icon and rollover icon for button
           btnClose.setRolloverIcon(CLOSE_TAB_ICON);
           btnClose.setRolloverEnabled(true);
           btnClose.setIcon(RGBGrayFilter.getDisabledIcon(btnClose, CLOSE_TAB_ICON));

           // Set border null so the button doesn't make the tab too big
           btnClose.setBorder(null);

           // Make sure the button can't get focus, otherwise it looks funny
           btnClose.setFocusable(false);

           // Put the panel together
           pnlTab.add(lblTitle);
           pnlTab.add(btnClose);

           // Add a thin border to keep the image below the top edge of the tab
           // when the tab is selected
           pnlTab.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));

           // Now assign the component for the tab
           tabbedPane.setTabComponentAt(pos, pnlTab);

           

           // Add the listener that removes the tab
           ActionListener listener = new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent e) {
               // The component parameter must be declared "final" so that it can be
               // referenced in the anonymous listener class like this.
               tabbedPane.remove(c);
             }
           };
           btnClose.addActionListener(listener);

           // Optionally bring the new tab to the front
           tabbedPane.setSelectedComponent(c);

           //-------------------------------------------------------------
           // Bonus: Adding a <Ctrl-W> keystroke binding to close the tab
           //-------------------------------------------------------------
           AbstractAction closeTabAction = new AbstractAction() {
             @Override
             public void actionPerformed(ActionEvent e) {
               tabbedPane.remove(c);
             }
           };

           // Create a keystroke
           KeyStroke controlW = KeyStroke.getKeyStroke("control W");

           // Get the appropriate input map using the JComponent constants.
           // This one works well when the component is a container.
           InputMap inputMap = c.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

           // Add the key binding for the keystroke to the action name
           inputMap.put(controlW, "closeTab");

           // Now add a single binding for the action name to the anonymous action
           c.getActionMap().put("closeTab", closeTabAction);
         }
     
     
    static  void updatebuttoms() {
   
     if (umtextg.canUndo())                          
        undoButtontemp.setEnabled(true);
     else
        undoButtontemp.setEnabled(false);
     if (umtextg.canRedo())                          
        redoButtontemp.setEnabled(true);
     else
        redoButtontemp.setEnabled(false);
   //  System.out.println(TemTextArea.getLocation().x+","+TemTextArea.getLocation().y);
    // textBusqueda.setLocation(mainPanelTemp.getBounds().width-TemTextArea.getLocation().x  -108 , (TemTextArea.getLocation().y*-1));
       //BuscarNextButtemp.setLocation(mainPanelTemp.getBounds().width-TemTextArea.getLocation().x  -130 ,  (TemTextArea.getLocation().y*-1));
       
 //    System.out.println(TemTextArea.getLocation().y*-1);
     
   //  System.out.println("UDATE");
       }

}

aqui agrega los menus y eventos.

Citar
   static void Preparejtex( final JTextArea editor)
   {
      
      final UndoManager umtext = new UndoManager();
      editor.getDocument().addUndoableEditListener(umtext);
      editor.setFont(new Font("Lucida Console", Font.PLAIN, 12));
      
      JPopupMenu popupMenuTAB = new JPopupMenu();
      addPopup(editor, popupMenuTAB);
      
      JMenuItem mntmDeshacer = new JMenuItem("Deshacer");
      popupMenuTAB.add(mntmDeshacer);
      mntmDeshacer.addActionListener( new ActionListener()
      { public void actionPerformed( ActionEvent e )
      {
          if (umtext.canUndo())   
             umtext.undo();
            if (umtext.canUndo())                         
               undoButtontemp.setEnabled(true);
              else
                 undoButtontemp.setEnabled(false);
           if (umtext.canRedo())                         
              redoButtontemp.setEnabled(true);
              else
                 redoButtontemp.setEnabled(false);} } );
      
      JMenuItem mntmRehacer = new JMenuItem("Rehacer");
      popupMenuTAB.add(mntmRehacer);
      mntmRehacer.addActionListener( new ActionListener()
      { public void actionPerformed( ActionEvent e ){
          if (umtext.canRedo())
            {umtext.redo();}
              updatebuttoms(); } } );



  //////////////////eventos

//// aqui pretendo recepcionar el evento del boton y mandar el jtextarea editarse .
      editor.getInputMap().put(KeyStroke.getKeyStroke('Z', Event.CTRL_MASK), "Undo");
      editor.getInputMap().put(KeyStroke.getKeyStroke('Y', Event.CTRL_MASK), "Redo");


   editor.getActionMap().put("Undo",
                  new AbstractAction("Undo") {
                private static final long serialVersionUID = 3L;
                public void actionPerformed(ActionEvent evt) {
                   try {if (editor.hasFocus())
                         {   if (umtext.canUndo()) {
                            umtext.undo(); }
                            updatebuttoms();}
                         }
                   catch (CannotUndoException e) {
                          }} });
         
         

          editor.getActionMap().put("Redo",
                  new AbstractAction("Redo") {
                private static final long serialVersionUID = 1L;
                public void actionPerformed(ActionEvent evt) {
                   try {
                      if (editor.hasFocus())
                         {   if (umtext.canRedo()) {
                            umtext.redo(); }
                         updatebuttoms();} }
                         catch (CannotUndoException e) {
                          }} });
                

}
Ahora bien si cada boton hace una accion como cortar o pegar no habria problema pero resulta que cada boton debe accionar al area de texto de la tab seleccionada lo que se me ocurrio es que el botton de cortar genere el evento ("CORTAR"); , cosa que puedo detectar en el mismo boton.

     public void actionPerformed(ActionEvent e) {
 
               System.out.println(e.toString());
               System.out.println(e.getActionCommand());  ///resultado evento CORTAR
            }

cutButtontm.setActionCommand("CORTAR");  


ahora bien mi duda es de que manera puedo propagar el evento a todos los elementos , y a su vez que el jtextarea de la tab selecionada lo pueda escuchar y asi poder editarlo. Cualquier pregunta, o sugerencia es bien venida , seguire buscando la solucion, saludos  ;-)







« Última modificación: 17 Septiembre 2013, 20:50 pm por stympy » En línea

stympy

Desconectado Desconectado

Mensajes: 12


Ver Perfil
Re: Editor texto multitab
« Respuesta #1 en: 17 Septiembre 2013, 21:10 pm »

creo que mi problema es que jtextarea no maneja ActionListener

cutButtontm.addActionListener((ActionListener)EventHandler.create(ActionListener.class, editor, "CORTAR"));


Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: No method called CORTAR on class javax.swing.JTextArea with no arguments


En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Editor de texto en php
PHP
wizache 6 14,353 Último mensaje 2 Agosto 2007, 01:59 am
por wizache
Ayuda con editor de texto
Programación Visual Basic
Alquimista_hack 1 1,345 Último mensaje 25 Agosto 2007, 03:09 am
por HaDeS, -
Ayuda con editor de texto
Java
danielo- 2 4,169 Último mensaje 29 Septiembre 2010, 06:06 am
por danielo-
ayuda con un editor de texto en c++
Programación C/C++
lucas85 0 2,121 Último mensaje 8 Noviembre 2010, 05:24 am
por lucas85
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines