2

He hecho un programa sencillo el cual me sirve para búsqueda de patrones REGEX y POSIX en java , así:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package proyecto_regexposix;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.*;
import javafx.stage.FileChooser;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author NP001
 */
public class Pantalla extends javax.swing.JFrame {

    private FileNameExtensionFilter filtro = new FileNameExtensionFilter("Archivo TXT", "txt");
    public Pantalla() {
        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() {

        Etiqueta_expresion = new javax.swing.JLabel();
        RegEX = new javax.swing.JTextField();
        BotonEjecutar = new javax.swing.JButton();
        BotonBorrar = new javax.swing.JButton();
        Etiqueta_ruta = new javax.swing.JLabel();
        txtRuta = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        TxtAREA = new javax.swing.JTextArea();
        Menu = new javax.swing.JMenuBar();
        MenuPrincipal = new javax.swing.JMenu();
        MenuAbrir = new javax.swing.JMenuItem();
        MenuAcerca = new javax.swing.JMenuItem();
        MenuSalir = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("PROYECTO METODOS FORMALES");

        Etiqueta_expresion.setText("EXPRESION");

        BotonEjecutar.setText("EJECUTAR!!!");
        BotonEjecutar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonEjecutarActionPerformed(evt);
            }
        });

        BotonBorrar.setText("BORRAR!!!");
        BotonBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonBorrarActionPerformed(evt);
            }
        });

        Etiqueta_ruta.setText("Ruta de archivo:");

        txtRuta.setEditable(false);

        TxtAREA.setColumns(20);
        TxtAREA.setLineWrap(true);
        TxtAREA.setRows(5);
        TxtAREA.setWrapStyleWord(true);
        jScrollPane2.setViewportView(TxtAREA);

        MenuPrincipal.setText("Archivo");
        MenuPrincipal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuPrincipalActionPerformed(evt);
            }
        });

        MenuAbrir.setText("Abrir");
        MenuAbrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuAbrirActionPerformed(evt);
            }
        });
        MenuPrincipal.add(MenuAbrir);

        MenuAcerca.setText("Acerca de ..");
        MenuAcerca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuAcercaActionPerformed(evt);
            }
        });
        MenuPrincipal.add(MenuAcerca);

        MenuSalir.setText("Salir");
        MenuSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuSalirActionPerformed(evt);
            }
        });
        MenuPrincipal.add(MenuSalir);

        Menu.add(MenuPrincipal);

        setJMenuBar(Menu);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(Etiqueta_expresion)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(RegEX))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(BotonEjecutar, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(BotonBorrar, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(Etiqueta_ruta)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtRuta)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Etiqueta_expresion)
                    .addComponent(RegEX, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Etiqueta_ruta)
                    .addComponent(txtRuta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BotonEjecutar)
                    .addComponent(BotonBorrar))
                .addContainerGap())
        );

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

    private void BotonBorrarActionPerformed(java.awt.event.ActionEvent evt) {                                            
        this.RegEX.setText("");
        this.TxtAREA.setText("");
        this.txtRuta.setText("");
    }                                           

    private void BotonEjecutarActionPerformed(java.awt.event.ActionEvent evt) {                                              
        String ObtenPatron=null;
        String QueReviso;
        ObtenPatron = RegEX.getText();
        QueReviso = TxtAREA.getText();
        Pattern Patron = Pattern.compile(ObtenPatron);
        Matcher Revisa = Patron.matcher(QueReviso);

        int cuenta = 0;
        while(Revisa.find()){
            cuenta++;
        }

        JOptionPane.showMessageDialog(null, cuenta);
    }                                             

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

    }                                             

    private void MenuAbrirActionPerformed(java.awt.event.ActionEvent evt) {                                          
        JFileChooser EligeArchivo = new JFileChooser();
        EligeArchivo.setFileFilter(filtro);
        int opcion = EligeArchivo.showOpenDialog(this);


        if (opcion == JFileChooser.APPROVE_OPTION){
            String nombreArchivo = EligeArchivo.getSelectedFile().getPath();
            String ruta = EligeArchivo.getSelectedFile().toString();
            txtRuta.setText(ruta);

            File archivo = new File(ruta);
        try {
            String Cadena;
            FileReader fr = new FileReader(archivo);
            BufferedReader br = new BufferedReader(fr);
            Cadena = br.readLine();
            TxtAREA.setText(Cadena);
            br.close();
            fr.close();
        }catch(IOException fnfe){};
        }
    }                                         

    private void MenuSalirActionPerformed(java.awt.event.ActionEvent evt) {                                          
        System.exit(0);
    }                                         

    private void MenuAcercaActionPerformed(java.awt.event.ActionEvent evt) {                                           
        JOptionPane.showMessageDialog(null, "Hecho por:\nNombre:Valdemar Benitez \nMatricula:0121520117");
    }                                          

    /**
     * @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(Pantalla.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Pantalla.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Pantalla.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Pantalla.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Pantalla().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton BotonBorrar;
    private javax.swing.JButton BotonEjecutar;
    private javax.swing.JLabel Etiqueta_expresion;
    private javax.swing.JLabel Etiqueta_ruta;
    private javax.swing.JMenuBar Menu;
    private javax.swing.JMenuItem MenuAbrir;
    private javax.swing.JMenuItem MenuAcerca;
    private javax.swing.JMenu MenuPrincipal;
    private javax.swing.JMenuItem MenuSalir;
    private javax.swing.JTextField RegEX;
    private javax.swing.JTextArea TxtAREA;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField txtRuta;
    // End of variables declaration                   
}

Sin embargo noté que cuando pongo un comando en Regex que esta mal. solo no lo ejecuta. por ejemplo digamos que yo tengo:

[a-z

el cual es un comando Posix que esta mal escrito al faltarle el cierre del corchete ] y pues al ser una función errónea el código no se ejecuta pero por consola me lanza el siguiente error

Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Unclosed character class near index 3 [a-z

Una vez puesto las cosas claras me surge lo siguiente duda

¿Existe alguna manera en que pueda yo sacar ese error de la consola y se muestre a través de una ventana OptionPane.showMessageDialog()?

1 respuesta 1

4

Lo puedes obtener mediante try/catch, de la siguiente manera, te dejo un ejemplo claro:

try {
       //parte del código que pueda generar errores
    } catch (Exception e) {
       //recuperamos el error
       String error=e.getMessage();
       //crear JoptionPane y pasar el valor de "error"
    }

Sólo reemplaza el comentario por el código en el cual se produce el error, y en el catch puedes lanzar el JOptionPane, recuperando el valor de la variable e, que contiene tu exepción.

3
  • 2
    Es válida la respuesta, solo añadir que para recuperar el mensaje se emplea e.getMessage()
    – Dev. Joel
    el 28 jul. 2017 a las 20:21
  • 1
    bueno, con Java en Android Studio así lo recupero, pero editaré la respuesta :) el 28 jul. 2017 a las 20:32
  • 1
    Muchisimas gracias me funciono perfecto!!! el 29 jul. 2017 a las 3:34

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.