[duvida] JTextArea + conteudo de um TXT

Boa tarde estou com essa difuldade, tenho logs gerados pelo meu sistema, e gostaria de colocar o valor deles na tela em um textArea

alguem pode dar uma luz?

E qual é sua dúvida??

como selecionar o arquivo é a primeira duvida, obs: sem o JFileChooser

e depois colocar o conteudo na JtextArea segunda duvidda

Para colocar o texto no textarea é só ler o arquivo e preencher o campo, não lembro muito bem quando eu usei um, mas me lembro que era estilo o JTextField

Selecionar o arquivo, como assim?? como vc quer seleciona-lo? quer abrir ele direto??

entao, como eu faço pra ler o arquivo txt antes de colocar na textarea?

Tutorial do GUJ sobre arquivos

http://www.guj.com.br/article.show.logic?id=13

[code] String arq = “logs/teste.txt”;

	try{
		BufferedReader in = new BufferedReader(new FileReader(arq));
		System.out.println("Arquivo lido!");
		String str, txt = "";
		while((str = in.readLine()) != null){
			txt += str;
		}
		tA.setText(txt);
	}
	catch (Exception e) {
		System.err.println("erro");
	}[/code]

era disso q eu tava falando, o arquivo foi lido

o problema agora é outro, quando eu visualizo o txt no eclispe fica certinho, ta pulando linha e tals.

agora quando eu abro o txt na mão ou coloco para visualizar o txt no TextArea, ai nao pula linha e zoa tudo o txt

esse é o codigo que gera o txt:

[code]public class GeradorDeLogs {

FileWriter file;
Data d = new Data();
String ação;

public void geraLogLogin(String user){
	ação = "login";
	String userLogin = user +"\t\t"+ ação + "\t" + d.mostraData() +"  "+ d.mostraHorario() ;
       try{   
          file = new FileWriter("logs/userteste.log", true);   
          userLogin += "\n\r";
          file.write(userLogin);            
          file.close();            
       }    
       catch(Exception e){  
          JOptionPane.showMessageDialog(null,"Erro ao gerar o log!","Atenção!!!",JOptionPane.ERROR_MESSAGE);  
       }  
}	
[/code]

Qual é seu SO??

Pelo \n\r acredito que seja windows, mas se eu não me engano, é ao contrário, é \r\n, primeiro vc dá o retorno de carro e depois faz uma linha nova.

O que aparece entre as linhas?

vou tentar inverter, ja posto o resultado

public void geraLogLogin(String user){ ação = "login"; String userLogin = "\r" + user +"\t"+ ação + "\t" + d.mostraData() +" "+ d.mostraHorario() + "\n" ; try{ file = new FileWriter("logs/userLog.log", true); userLogin += "\r\n"; file.write(userLogin); file.close(); } catch(Exception e){ JOptionPane.showMessageDialog(null,"Erro ao gerar o log!","Atenção!!!",JOptionPane.ERROR_MESSAGE); } }

perfeito valeu! inverti os \n\r por \r\n e coloquei um \r no começo da string

:wink:

agora o problema é, o conteudo txt entrar no textarea:

Primeiro, criar um scrollpane para a jtextarea,

fiz da seguinte maneira: JScrollPane painelRolagem = new JScrollPane(); painelRolagem.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); painelRolagem.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

depois adicionei a textarea, mais nao funfa.

alguem ai?

o teste que eu fiz fica assim:

BarraDeRolagem() {
		JFrame frame = new JFrame();
		frame.setTitle("teste");
		frame.setLocation(300, 300);
		frame.setSize(400, 400);

		JPanel panel = new JPanel();
		frame.getContentPane().add(panel);
		panel.setLayout(null);

                JTextArea tA = new JTextArea(7,30);
		tA.setLineWrap(true);
		tA.setBounds(10, 80, 303, 70);
		tA.setMargin(new  Insets(5,5,5,5));

               
               JScrollPane scrollPanel = new JScrollPane();   
	       scrollPanel.setViewportView(tA);
	       scrollPanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);  
	       scrollPanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); 

               String arq = "logs/userLog.log";
		
		try{
			BufferedReader in = new BufferedReader(new FileReader(arq));
			System.out.println("Arquivo lido!");
			String str, txt = "";
			while((str = in.readLine()) != null){
				txt += str;
			}
			tA.setText(txt);
		}
		catch (Exception e) {
			System.err.println("erro");
		}

                panel.add(tA);
		panel.add(scrollPanel);
		
		frame.setVisible(true);
	}

}

Ta carregando a textarea com o conteudo certinho, mais a scrollbar nao aparece =/

ja fiz de tudo, teve uma vez q a scrollbar aparaceu mais nao dentro da textarea,

alguem pode me ajudar? :cry:

Para escrever num arquivo use o PrintWriter, além do FileWriter. O PrintWriter tem métodos como println e prinf, que já pulam a linha corretamente.

Para fazer isso, basta colocar o seu FileWriter dentro do PrintWriter:

PrintWriter out = new PrintWriter(file);

E aí usar os métodos do PrintWriter.

Para ler arquivos, use a classe Scanner.

Para scrollbar num JTextArea:

  1. Crie um ScrollPane;
  2. Crie um JTextArea;
  3. Coloque o JTextArea dentro do JScrollPane;
  4. Coloque o JScrollPane na tela.

ja tentei fazer isso e não funfou! :cry:

Alguem pode me dar um exemplo com layout null?

Não.

Você não deve usar layout null. Nunca, jamais. É um dos erros graves no desenvolvimento de aplicações Swing.

O layout null não funciona. Ele não permite redimensionamento de tela. Ele não é multi-plataforma. Ele ferra até mesmo se você mudar a resolução do seu monitor. Não utilize.

Portanto, jamais darei um exemplo com layout null.

Mas eu posso dar um exemplo usando layout managers:

[code]package leituraarquivo;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class LeituraFrame extends JFrame {

private JTextField txtArquivo = null;
private JTextArea txtTexto = null;
private JScrollPane scrlTexto = null;
private JButton btnAbrir = null;
private JButton btnSalvar = null;
private JPanel pnlArquivo = null;
private JPanel pnlBotoes = null;
private JFileChooser fc = new JFileChooser();

public LeituraFrame() {
    super("Ler e gravar arquivos");
    setSize(800, 600);
    setLocationRelativeTo(null);
    setLayout(new BorderLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    add(getPnlArquivo(), BorderLayout.NORTH);
    add(getScrlTexto(), BorderLayout.CENTER);
}

public JPanel getPnlArquivo() {
    if (pnlArquivo != null) {
        return pnlArquivo;
    }
    pnlArquivo = new JPanel(new BorderLayout());
    pnlArquivo.add(getTxtArquivo(), BorderLayout.CENTER);
    pnlArquivo.add(getPnlBotoes(), BorderLayout.EAST);
    return pnlArquivo;
}

public JTextField getTxtArquivo() {
    if (txtArquivo != null) {
        return txtArquivo;
    }
    txtArquivo = new JTextField();
    txtArquivo.setEditable(false);
    return txtArquivo;
}

public JPanel getPnlBotoes() {
    if (pnlBotoes != null) {
        return pnlBotoes;
    }
    pnlBotoes = new JPanel(new FlowLayout());
    pnlBotoes.add(getBtnAbrir());
    pnlBotoes.add(getBtnSalvar());
    return pnlBotoes;
}

public JButton getBtnAbrir() {
    if (btnAbrir != null) {
        return btnAbrir;
    }
    btnAbrir = new JButton();
    btnAbrir.setText("Abrir");
    btnAbrir.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            abrir();
        }
    });

    return btnAbrir;
}

public JButton getBtnSalvar() {
    if (btnSalvar != null) {
        return btnSalvar;
    }

    btnSalvar = new JButton();
    btnSalvar.setText("Salvar");
    btnSalvar.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            salvar();
        }
    });

    return btnSalvar;
}

public JScrollPane getScrlTexto() {
    if (scrlTexto != null) {
        return scrlTexto;
    }

    scrlTexto = new JScrollPane(getTxtTexto());
    return scrlTexto;
}

private JTextArea getTxtTexto() {
    if (txtTexto != null) {
        return txtTexto;
    }

    txtTexto = new JTextArea();
    return txtTexto;
}

private void abrir() {
    if (fc.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) {
        return;
    }
    getTxtArquivo().setText(fc.getSelectedFile().getAbsolutePath());

    StringBuilder texto = new StringBuilder();
    try {
        Scanner scan = new Scanner(fc.getSelectedFile());
        while (scan.hasNextLine()) {
            texto.append(scan.nextLine()).append("\n");
        }

        getTxtTexto().setText(texto.toString());
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, "Não foi possível ler o arquivo solicitado.");
        e.printStackTrace();
    }
}

private void salvar() {
    if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) {
        return;
    }

    PrintWriter pw = null;
    try {
        pw = new PrintWriter(fc.getSelectedFile());
        Scanner scan = new Scanner(getTxtTexto().getText());
        while (scan.hasNextLine()) {
            pw.print(scan.nextLine());

            //Evita a inserção de uma linha em branco no final do arquivo
            //Se não for problema para você, pode deixar println na linha
            //de cima direto.
            if (scan.hasNextLine()) 
                pw.println();
        }
        pw.flush();
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, "Não foi possível salvar o arquivo.");
        e.printStackTrace();
    } finally {
        if (pw != null) {
            pw.close();
        }
    }
}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            LeituraFrame lf = new LeituraFrame();
            lf.setVisible(true);
        }
    });
}

}
[/code]

blz, obrigado pelo exemplo ViniGodoy,

mais como eu faço pra colocar um componente em uma coordenada(x,y) ?

deixa eu explicar melhor.

Queria saber se tem e qual o gerenciador de layout que possa alterar o tamanho de um JComponent e colocar ele em qualquer lugar do frame.

Com o layout(null), é possivel fazer isso.

bt.setBounds(10,10,100,20);

depois disso é só colocar no panel, mais como vc disse nao deve usar layout null. tem algum outro tipo de layout que tenha os mesmos recursos?