Editor de Textos em Java

18 respostas
P

Olá pessoal, estou fazendo um bloco de textos em java e quando eu estou fazendo o botão ABRIR, ele dá uma linha de comando errada… por favor me ajudem, não sei como resolver. Obrigado
Este é o código do Botão Abrir:

try{
            fabrir = new FileDialog(this, "Abrir Arquivo", FileDialog.LOAD);
            fabrir.show();
            if(fabrir.getFile()==null);
            {
                return;
            }

//A Linha que está em Negrito, é a que dá erro
//Dá erro no getDirectory() e no getFile();, quando eu arrumo, dá erro na variável
nomearquivo = fabrir.getDirectory()+ nomearquivo = fabrir.getFile();

FileReader in=new FileReader(nomearquivo);
            String texto;
            texto="";
            int I;
            I = in.read();
            while (I!=1){
                texto=texto+(char)I;
                I=in.read();
            }
            jtArea.setText(texto);
            in.close();
        } catch (java.io.IOException e){
            JOptionPane.showMessageDialog(null, "Erro ao carregar o arquivo");
}

[size=“11”][color=“red”]* Editado: Lembre-se de utilizar BBCode em seus códigos - Ratinho[/color][/size] :joia:

Seja Livre Use Linux!!!

18 Respostas

J

Usa isso:
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JFileChooser.html

P

Amigo pode me explicar? eu não entendi direito…
Você não sabe porque daquele erro?
Obrigado
:grin:

J

Use JFileChooser, nunca vi ninguem usando essa classe FileDialog!

Sobre o erro:
Mas olha só o que você está fazendo:

nomearquivo = fabrir.getDirectory()+ nomearquivo = fabrir.getFile();

O que exatamente você tentou fazer aí?!!!

Não seria isso?

nomearquivo = fabrir.getDirectory()+fabrir.getFile();
P
Vou colocar aqui embaixo todo o código do botão Abrir:

try{

fabrir = new FileDialog(this, Abrir Arquivo, FileDialog.LOAD);

fabrir.show();

if(fabrir.getFile()==null);

{

return;

}

nomearquivo = fabrir.getDirectory()+fabrir.getFile();

FileReader in=new FileReader(nomearquivo);

String texto;

texto="";

int I;

I = in.read();

while (I!=1){

texto=texto+(char)I;

I=in.read();

}

jtArea.setText(texto);

in.close();

} catch (java.io.IOException e){

JOptionPane.showMessageDialog(null, Erro ao carregar o arquivo);

}

Tentei colocar essa linha:
nomearquivo = fabrir.getDirectory()+fabrir.getFile();
como você colocou
mas ela dá o seguinte erro:
UNREACHABLE STATEMENT

J

UNREACHABLE STATEMENT significa que essa linha nunca será alcançada, em nenhuma circunstancia… nesse caso deve ter algo que impede de chegar até ela…

coloca o codigo do metodo aí…

P

Aqui está todo o código do meu programa:
/*

  • Editor.java
  • Created on 23 de Maio de 2006, 10:14
    */

/**
*

  • @author  maq02
    
    <em>/
    
    import javax.swing.JOptionPane;
    
    import <a href="http://java.io">java.io</a>.</em>;
    
    import java.awt.FileDialog;
    
    public class Editor extends javax.swing.JFrame {
    
    /** Creates new form Editor <em>/
    
    public Editor() {
    
    initComponents();
    
    }
    
    FileDialog fabrir, fsalvarcomo;
    
    String nomearquivo, texto;
    
    int neg, ita;
    
    /</em>* 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.
      
      */
      
      // <editor-fold defaultstate=collapsed desc=" Generated Code ">//GEN-BEGIN:initComponents
      
      private void initComponents() {
      
      jScrollPane2 = new javax.swing.JScrollPane();
      
      jtArea = new javax.swing.JEditorPane();
      
      jMenuBar1 = new javax.swing.JMenuBar();
      
      jMenu1 = new javax.swing.JMenu();
      
      Novo = new javax.swing.JMenuItem();
      
      Abrir = new javax.swing.JMenuItem();
      
      jSeparator1 = new javax.swing.JSeparator();
      
      Salvar = new javax.swing.JMenuItem();
      
      SalvarComo = new javax.swing.JMenuItem();
      
      jSeparator2 = new javax.swing.JSeparator();
      
      Sair = new javax.swing.JMenuItem();
      
      jMenu2 = new javax.swing.JMenu();
      
      Copiar = new javax.swing.JMenuItem();
      
      Recortar = new javax.swing.JMenuItem();
      
      Colar = new javax.swing.JMenuItem();
      
      jSeparator3 = new javax.swing.JSeparator();
      
      Negrito = new javax.swing.JCheckBoxMenuItem();
      
      Italico = new javax.swing.JCheckBoxMenuItem();
      
      SelecionarTudo = new javax.swing.JMenuItem();
      

      setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
      jScrollPane2.setViewportView(jtArea);

      jMenu1.setMnemonic(a);
      
      jMenu1.setText(Arquivo);
      
      Novo.setMnemonic(n);
      
      Novo.setText(Novo);
      
      Novo.addActionListener(new java.awt.event.ActionListener() {
      
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      
      NovoActionPerformed(evt);
      
      }
      
      });
      

      jMenu1.add(Novo);

      Abrir.setMnemonic(a);
      
      Abrir.setText(Abrir);
      
      Abrir.addActionListener(new java.awt.event.ActionListener() {
      
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      
      AbrirActionPerformed(evt);
      
      }
      
      });
      

      jMenu1.add(Abrir);

      jMenu1.add(jSeparator1);

      Salvar.setMnemonic(s);
      
      Salvar.setText(Salvar);
      
      Salvar.addActionListener(new java.awt.event.ActionListener() {
      
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      
      SalvarActionPerformed(evt);
      
      }
      
      });
      

      jMenu1.add(Salvar);

      SalvarComo.setMnemonic(c);
      
      SalvarComo.setText(Salvar Como);
      
      SalvarComo.addActionListener(new java.awt.event.ActionListener() {
      
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      
      SalvarComoActionPerformed(evt);
      
      }
      
      });
      

      jMenu1.add(SalvarComo);

      jMenu1.add(jSeparator2);

      Sair.setMnemonic(r);
      
      Sair.setText(Sair);
      
      Sair.addActionListener(new java.awt.event.ActionListener() {
      
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      
      SairActionPerformed(evt);
      
      }
      
      });
      

      jMenu1.add(Sair);

      jMenuBar1.add(jMenu1);

      jMenu2.setMnemonic(e);
      
      jMenu2.setText(Editar);
      
      Copiar.setMnemonic(c);
      
      Copiar.setText(Copiar);
      
      Copiar.addActionListener(new java.awt.event.ActionListener() {
      
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      
      CopiarActionPerformed(evt);
      
      }
      
      });
      

      jMenu2.add(Copiar);

      Recortar.setMnemonic(r);
      
      Recortar.setText(Recortar);
      
      Recortar.addActionListener(new java.awt.event.ActionListener() {
      
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      
      RecortarActionPerformed(evt);
      
      }
      
      });
      

      jMenu2.add(Recortar);

      Colar.setMnemonic(‘o’);

      Colar.setText(Colar);
      
      Colar.addActionListener(new java.awt.event.ActionListener() {
      
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      
      ColarActionPerformed(evt);
      
      }
      
      });
      

      jMenu2.add(Colar);

      jMenu2.add(jSeparator3);

      Negrito.setMnemonic(N);
      
      Negrito.setText(Negrito);
      
      Negrito.addActionListener(new java.awt.event.ActionListener() {
      
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      
      NegritoActionPerformed(evt);
      
      }
      
      });
      

      jMenu2.add(Negrito);

      Italico.setMnemonic(I);
      
      Italico.setText(Italico);
      
      Italico.addActionListener(new java.awt.event.ActionListener() {
      
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      
      ItalicoActionPerformed(evt);
      
      }
      
      });
      

      jMenu2.add(Italico);

      SelecionarTudo.setMnemonic(S);
      
      SelecionarTudo.setText(Selecionar Tudo);
      
      SelecionarTudo.addActionListener(new java.awt.event.ActionListener() {
      
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      
      SelecionarTudoActionPerformed(evt);
      
      }
      
      });
      

      jMenu2.add(SelecionarTudo);

      jMenuBar1.add(jMenu2);

      setJMenuBar(jMenuBar1);

      org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
      
      getContentPane().setLayout(layout);
      
      layout.setHorizontalGroup(
      
      layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
      
      .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE)
      
      );
      
      layout.setVerticalGroup(
      
      layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
      
      .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)
      
      );
      
      pack();
      
      java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
      
      java.awt.Dimension dialogSize = getSize();
      
      setLocation((screenSize.width-dialogSize.width)/2,(screenSize.height-dialogSize.height)/2);
      
      }// </editor-fold>//GEN-END:initComponents
      
    private void ItalicoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ItalicoActionPerformed
    
    // TODO add your handling code here:
    
    if (Italico.getState()==true){
    
    ita = 2;
    
    } else{
    
    ita=0;
    
    }
    
    jtArea.setFont(new java.awt.Font(Arial, neg+ita, 20));
    
    }//GEN-LAST:event_ItalicoActionPerformed
    
    private void NegritoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NegritoActionPerformed
    
    // TODO add your handling code here:
    
    if (Negrito.getState()==true){
    
    neg = 1;
    
    } else{
    
    neg = 0;
    
    }
    
    jtArea.setFont(new java.awt.Font(Arial, neg+ita, 20));
    
    }//GEN-LAST:event_NegritoActionPerformed
    

    private void SelecionarTudoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SelecionarTudoActionPerformed
    // TODO add your handling code here:
    jtArea.selectAll();
    }//GEN-LAST:event_SelecionarTudoActionPerformed

    private void ColarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ColarActionPerformed
    // TODO add your handling code here:
    jtArea.paste();
    }//GEN-LAST:event_ColarActionPerformed

    private void RecortarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RecortarActionPerformed
    // TODO add your handling code here:
    jtArea.cut();
    }//GEN-LAST:event_RecortarActionPerformed

    private void CopiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CopiarActionPerformed
    // TODO add your handling code here:
    jtArea.copy();
    }//GEN-LAST:event_CopiarActionPerformed

    private void SairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SairActionPerformed
    // TODO add your handling code here:
    this.dispose();
    }//GEN-LAST:event_SairActionPerformed

    private void SalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SalvarActionPerformed
    
    // TODO add your handling code here:
    
    if (nomearquivo.length()!=0){
    
    try{
    
    FileWriter out = new FileWriter(nomearquivo);
    
    out.write(jtArea.getText());
    
    out.close();
    
    } catch (java.io.IOException e){
    
    JOptionPane.showMessageDialog(null, Erro ao salvar o arquivo);
    
    }
    
    }
    
    }//GEN-LAST:event_SalvarActionPerformed
    
    private void AbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AbrirActionPerformed
    
    // TODO add your handling code here:
    
    try{
    
    fabrir = new FileDialog(this, Abrir Arquivo, FileDialog.LOAD);
    
    fabrir.show();
    
    if(fabrir.getFile()==null);
    
    {
    
    return;
    
    }
    
    nomearquivo = fabrir.getDirectory()+fabrir.getFile();
    
    FileReader in=new FileReader(nomearquivo);
    
    String texto;
    
    texto="";
    
    int I;
    
    I = in.read();
    
    while (I!=1){
    
    texto=texto+(char)I;
    
    I=in.read();
    
    }
    
    jtArea.setText(texto);
    
    in.close();
    
    } catch (java.io.IOException e){
    
    JOptionPane.showMessageDialog(null, Erro ao carregar o arquivo);
    
    }
    
    }//GEN-LAST:event_AbrirActionPerformed
    
    private void SalvarComoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SalvarComoActionPerformed
    
    // TODO add your handling code here:
    
    fsalvarcomo = new FileDialog(this, Salvar Como, FileDialog.SAVE);
    
    //configura o tipo de caixa e o título da mesma
    
    try{
    
    fsalvarcomo.show();
    
    //exibe a caixa
    
    if (fsalvarcomo.getFile()==null);
    
    {
    
    return;
    
    }
    
    // caso o usuário não digite o nome do arquivo ou clique no botão
    
    // cancelar será returnado com a gravação do arquivo
    
    nomearquivo = fsalvarcomo.getDirectory()+fabrir.getFile();
    
    FileWriter out = new FileWriter(nomearquivo);
    
    out.write(jtArea.getText());
    
    out.close();
    
    } catch (java.io.IOException e){
    
    JOptionPane.showMessageDialog(null, Erro ao carregar o arquivo);
    
    }
    
    }//GEN-LAST:event_SalvarComoActionPerformed
    
    private void NovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NovoActionPerformed
    
    // TODO add your handling code here:
    
    String nomearquivo;
    
    nomearquivo = “”;
    
    jtArea.setText("");
    
    }//GEN-LAST:event_NovoActionPerformed
    

    /**

    • @param args the command line arguments
      */
      public static void main(String args[]) {
      java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
      new Editor().setVisible(true);
      }
      });
      }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    
    private javax.swing.JMenuItem Abrir;
    
    private javax.swing.JMenuItem Colar;
    
    private javax.swing.JMenuItem Copiar;
    
    private javax.swing.JCheckBoxMenuItem Italico;
    
    private javax.swing.JCheckBoxMenuItem Negrito;
    
    private javax.swing.JMenuItem Novo;
    
    private javax.swing.JMenuItem Recortar;
    
    private javax.swing.JMenuItem Sair;
    
    private javax.swing.JMenuItem Salvar;
    
    private javax.swing.JMenuItem SalvarComo;
    
    private javax.swing.JMenuItem SelecionarTudo;
    
    private javax.swing.JMenu jMenu1;
    
    private javax.swing.JMenu jMenu2;
    
    private javax.swing.JMenuBar jMenuBar1;
    
    private javax.swing.JScrollPane jScrollPane2;
    
    private javax.swing.JSeparator jSeparator1;
    
    private javax.swing.JSeparator jSeparator2;
    
    private javax.swing.JSeparator jSeparator3;
    
    private javax.swing.JEditorPane jtArea;
    
    // End of variables declaration//GEN-END:variables
    

}

Se puder me ajudar, muito obrigado.

J

if&#40;fabrir.getFile&#40;&#41;==null&#41;; &#123; return; &#125; nomearquivo = fabrir.getDirectory&#40;&#41;+fabrir.getFile&#40;&#41;;

Note o return, ele vai terminar o metodo antes de chegar na linha onde pega o nome do arquivo, sempre, pois ele não está dentro do if, tem um ; depois do if, ou seja, quando fabrir.getFile() for null, nada será feito, e logo apos sendo null ou não será executado o return e nunca chegará na linha debaixo, tira esse ;

P

Ok!! Deu certo!!! ele aparece a caixa, mas no momento de abrir, ele não abre, não aparece o texto na tela…
Como você mandou modificar eu modifiquei, ele ficou assim (é o que eu espero que você tenha pensado assim):

try{

fabrir = new FileDialog(this, Abrir Arquivo”, FileDialog.LOAD);

fabrir.show();

nomearquivo = fabrir.getDirectory()+fabrir.getFile();

FileReader in=new FileReader(nomearquivo);

String texto;

texto="";

int I;

I = in.read();

while (I!=1){

texto=texto+(char)I;

I=in.read();

}

jtArea.setText(texto);

in.close();
} catch (java.io.IOException e){
        JOptionPane.showMessageDialog(null, "Erro ao carregar o arquivo");
    }
J

Coloque mais uma coisa aí:

nomearquivo = fabrir.getDirectory&#40;&#41;+File.separator+fabrir.getFile&#40;&#41;;

Se der errado, coloque a exceção aqui…

P

Não aparece nada na tela, na minha tela tem um JTextArea, mas não aparece nada, o código reformado é este:

try{

fabrir = new FileDialog(this, Abrir Arquivo, FileDialog.LOAD);

fabrir.show();

if(fabrir.getFile()==null);

nomearquivo = fabrir.getDirectory()+fabrir.getFile();

nomearquivo = fabrir.getDirectory()+File.separator+fabrir.getFile();

FileReader in=new FileReader(nomearquivo);

String texto;

texto="";

int I;

I = in.read();

while (I!=1){

texto=texto+(char)I;

I=in.read();

}

jtArea.setText(texto);

in.close();

} catch (java.io.IOException e){

JOptionPane.showMessageDialog(null, Erro ao carregar o arquivo);

}
J

Isso não está errado?

Acho que deveria ser -1

while &#40;I!=-1&#41;&#123;
P

Muito Obrigado Amigo!!! Funcionou normalmente!!!
Você sabe alguma linha de comando para deixar centralizado, esquerdo, direito, justificado?
Outra coisa:
O botão Salvar como abre normal, mas não salva o arquivo
Aqui está o código:

fsalvarcomo = new FileDialog(this, Salvar Como, FileDialog.SAVE);

try{

fsalvarcomo.show();

nomearquivo = fsalvarcomo.getDirectory()+fabrir.getFile();

FileWriter out = new FileWriter(nomearquivo);

out.write(jtArea.getText());

out.close();

} catch (java.io.IOException e){

JOptionPane.showMessageDialog(null, Erro ao carregar o arquivo);

}

Obrigado amigo!!!

J

Entre na pasta de exemplos do JDK, lá tem dois editores de texto, um simples e um com estilo (direita, esquerda, centralizado, negrito, etc)…

Só você dar uma olhada no codigo:

pasta_jdk/demo/jfc/Notepad/
pasta_jdk/demo/jfc/Stylepad/

P

E você sabe dizer o problema do salvar como?
Obrigado

J
nomearquivo = fsalvarcomo.getDirectory&#40;&#41;+File.separator+fabrir.getFile&#40;&#41;;
P
Não funcionou. Coloquei assim:

nomearquivo = fsalvarcomo.getDirectory()+fabrir.getFile();

nomearquivo = fsalvarcomo.getDirectory()+File.separator+fabrir.getFile();
E depois assim:

(Sem a linha de cima)

nomearquivo = fsalvarcomo.getDirectory()+File.separator+fabrir.getFile();

E não funcionou

J

Não entendi o que fez… na minha opinião deveria usar JFileChooser, é melhor pra você!

P
Então me diz onde eu tenho que substituir no meu programa:

fsalvarcomo = new FileDialog(this, Salvar Como, FileDialog.SAVE);

try{

fsalvarcomo.show();

nomearquivo = fsalvarcomo.getDirectory()+fabrir.getFile();

nomearquivo = fsalvarcomo.getDirectory()+File.separator+fabrir.getFile();

FileWriter out = new FileWriter(nomearquivo);

out.write(jtArea.getText());

out.close();

} catch (java.io.IOException e){

JOptionPane.showMessageDialog(null, Erro ao gravar o arquivo);

}

Obrigado

Criado 23 de maio de 2006
Ultima resposta 24 de mai. de 2006
Respostas 18
Participantes 2