Desenvolvendo um pequeno Editor de Texto

6 respostas
nois_159

Olá pessoal!!!

Estou tentando desenvolver junto com um amigo meu, um pequeno editor de texto, pra poder fortalecer os conhecimentos de pilha e fila.
Daí oque acontece, na hora que está digitando uma palavra e dou um espaço é jogado no nó da lista, então… declarei que

palavras = jTextArea1.getText().split(" ");

certo??? No caso, quando der um espaço depois que digitar algumas letras, ele identifica que aquilo é uma palavra, pois guardará dentro da lista, daí se caso eu gostaria de voltar… “desfazer”, ele voltaria a palavra anterior…
ai que está o problema, está dando aquele erro chato Exception… então fiz uma comparação… assim…

if(palavras.length>1){ No palavra = new No(); palavra.setPalavra(palavras[palavras.length]); lista1.adiciona(palavra); }

só que ele vai, mais não por muito tempo ele continua no mesmo erro Exception. Bom, eu nunca tinha feito esse tipo de condição, onde pegava a palavra e jogava ele pro nó, no Word por exemplo, é por tempo certo, aqui estou querendo só por por palavras mesmo… só pra fortalecer o conhecimento.

Agora falto mesmo só um pouco mais de experiência né, mais se puderem me ajudar…

Agradeço muito pela atenção!!

6 Respostas

W

Exception é generico explique qual o erro que acontece coloque um probo try catch e manda dar um printStacktrace() e post o erro que está acontecendo

nois_159

Me desculpe de não conseguir expressar corretamente, bom.. vou mostrar todo o meu código, é simples, e está como Jfram.. oks

lá vamos nós!!!

public class No {

    private String palavra;
    private No prox;

    /**
     * @return the palavra
     */
    public String getPalavra() {
        return palavra;
    }

    /**
     * @param palavra the palavra to set
     */
    public void setPalavra(String palavra) {
        this.palavra = palavra;
    }

    /**
     * @return the prox
     */
    public No getProx() {
        return prox;
    }

    /**
     * @param prox the prox to set
     */
    public void setProx(No prox) {
        this.prox = prox;
    }

    

}

public class Lista {

    private No inicio;

    public void adiciona(No novo) {
        if (inicio == null) {
            inicio = novo;
        } else {
            novo.setProx(inicio);
            inicio = novo;
        }
    }

    public No remove() {
        No aux= inicio;
        inicio = inicio.getProx();
        return aux;
    }
    
    public void imprime(){
        No aux = inicio;
        while (aux!=null){
            System.out.println(aux.getPalavra());
            aux = aux.getProx();
        }
    }
}

public class Main {

    public static void main(String args[]) {
        NewJFrame a = new NewJFrame();
        a.setVisible(true);
    }
}

public class NewJFrame extends javax.swing.JFrame {

    Lista lista1;
    Lista lista2;
    String[] palavras;

    public NewJFrame() {
        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() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jToolBar1 = new javax.swing.JToolBar();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextArea1KeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jTextArea1);

        jToolBar1.setRollover(true);

        jButton1.setText("Desfazer");
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton1);

        jButton2.setText("Refazer");
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButton2);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 444, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
                .addContainerGap())
        );

        jMenu1.setText("Arquivo");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Editar");

        jMenuItem1.setText("Desfazer");
        jMenu2.add(jMenuItem1);

        jMenuItem2.setText("Refazer");
        jMenu2.add(jMenuItem2);

        jMenuBar1.add(jMenu2);

        jMenu3.setText("Ajuda");
        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

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

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

//O NEGOCIO DO MEU CODIGO ESTÁ AQUI, ONDE IREI DIGITAR DENTRO DO MEU JTEXTAREA1
// DAI ELE JA IDENTIFICA QUE O "ESPAÇO" ("  "), E ALOCA NA LISTA, SEQUENCIALMENTE, NO CASO.. INICIO DA LISTA
// DAI QUANDO EU QUISER DESFAZER, ELE RETIRA A ULTIMA PALAVRA DIGITADA...                       

    private void jTextArea1KeyReleased(java.awt.event.KeyEvent evt) {                                       
        // TODO add your handling code here:
        //System.out.println("s " + jTextArea1.getText());
        palavras = jTextArea1.getText().split(" ");
        if(palavras.length>1){
            No palavra = new No();
            palavra.setPalavra(palavras[palavras.length]);
            lista1.adiciona(palavra);
        }
    }                                      

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        jTextArea1.setText(lista1.remove().getPalavra());
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration                   
}

bom, é isso, coloquei onde é o lugar que está dando problema, no caso, quero que ele identifica que estou digitando as letras, daí quando der o primeiro espaço, ele identifica aquele conjuto de letra é uma palavra, e irá alocar na lista, que por sua vez, terá os botões que irá desfazer e refazer... bom, é isso.

Muito obrigado pela atenção.

pmlm

Isto dá ArrayIndexOutOfBoundsException porque não podes aceder ao indice igual ao tamanho do array. Se queres aceder ao último elemento do array é palavra.setPalavra(palavras[palavras.length-1]);

nois_159

Muito obrigado pela atenção pmlm…

Então… isso eu já tinha feito de primeiro… o erro daria assim > Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException …
isso que fiquei em dúvida… porque é esse erro??

muito obrigado mesmo mais uma vez pela atenção!

Lucas_Abbatepaolo

Este erro significa q vc esta tentando acessar algo q é nulo…

veja em qual linha da este erro …

pmlm

nois_159:
Muito obrigado pela atenção pmlm…

Então… isso eu já tinha feito de primeiro… o erro daria assim > Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException …
isso que fiquei em dúvida… porque é esse erro??

muito obrigado mesmo mais uma vez pela atenção!

A variável lista1 não está inicializada.

Criado 7 de outubro de 2010
Ultima resposta 7 de out. de 2010
Respostas 6
Participantes 4