Dúvida Swing [RESOLVIDO]

9 respostas
jeloy

Bom dia pessoal…

sou iniciante java, e estou tendo uma dúvida em relação a aplicação desktop

tenho uma classe que recebe como parâmetro o caminho de um arquivo txt, e imprime o mesmo no console.

funciona normal…

mas quero passar isto para o GUI…

criei uma visual class e defini ela pra passar o parametro para esta classe e chama-la ao clicar em ok. até aí tudo bem… a classe é chamada e o txt é impressos no console. Queria saber qual o melhor componente para se exibir textos no SWING e algumas dicas…
alguem pode ajudar?

valeu1

9 Respostas

otaviojava

O componente em swing é o JTextArea.
Você pega o texto e passa para uma String em seguida você trata como quiser e logo depois joga para esse componente.

jeloy

otaviojava:
O componente em swing é o JTextArea.
Você pega o texto e passa para uma String em seguida você trata como quiser e logo depois joga para esse componente.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class ReadTxt {
	String caminho;
	String arquivo;
	String sufixo;
	String ler = caminho + arquivo + sufixo;
	JFrame janela = new JFrame();
	JPanel painel = new JPanel();
	JTextArea texto = new JTextArea(40, 10);
	String str;
	
	public ReadTxt(String caminho) throws IOException {
		BufferedReader in = null;  
            try {  
                 in = new BufferedReader(new FileReader(caminho));  
                 
                 while ( (str = in.readLine()) != null ) {  
                	janela.setTitle(caminho);
             		janela.setSize(600, 600);
             		janela.add(painel);
             		painel.add(texto);
             		texto.setSize(500,500);
             		texto.setText(str);
             		janela.setVisible(true);
             		
                	 
                	 System.out.println( str );  
                	 
                 }  
              } catch (IOException e) {  
               e.printStackTrace();  
              }finally{  
               if( in != null ){  
                  in.close();  
               }  
              }
	}
	
}

certo, eu tentei usar ele, mas ele nao monta corretamente no meu loop…ta imprimindo no TextArea somente a primeira linha.
desculpa minha ignorancia, as vezes pode ser coisa fácil mas estou iniciando hehehe…

na System.out.println ela imprime todas as linhas, mas é pq executa até o fim do loop.

drigo.angelo
Vai lendo o texto e colocando em uma string, ex:
String texto = "";
while  ( (str = in.readLine()) != null  ) {    
                    texto += str;
                       
                 }
janela.setTitle(caminho);  
janela.setSize(600, 600);  
janela.add(painel);  
painel.add(texto);  
texto.setSize(500,500);  
texto.setText(texto);  
janela.setVisible(true);  
                      
                       
System.out.println( texto );
otaviojava
drigo.angelo:
Vai lendo o texto e colocando em uma string, ex:
String texto = "";
while  ( (str = in.readLine()) != null  ) {    
                    texto += str;
                       
                 }
janela.setTitle(caminho);  
janela.setSize(600, 600);  
janela.add(painel);  
painel.add(texto);  
texto.setSize(500,500);  
texto.setText(texto);  
janela.setVisible(true);  
                      
                       
System.out.println( texto );

Foi assim mesmo que eu quiz dizer:

Joga toda a informação na String e depois você joga para o textArea

ViniGodoy

Lembre-se que concatenações em String em loops são extremamente lentas.

O ideal é usar um StringBuilder:

StringBuilder texto = new StringBuilder(); while ( (str = in.readLine()) != null ) { texto.append(str); } System.out.println( texto.toString() );

ViniGodoy

Veja um exemplo completo e funcional em:
http://www.guj.com.br/java/148485-resolvido-javalangnullpointerexception-ao-gerar-arquivo-txt#803214

A

Ao invés de usar texto += str;, crie um StringBuilder e vá adicionando o texto. Por String em Java ser um objeto imutável, toda vez que você usa o operador += você cria uma nova String no heap sem necessidade.
Ex:

StringBuilder sb = new StringBuilder(texto);
sb.append(str);
textArea.setText(sb.toString());
ViniGodoy

O textArea também tem o método append. E a vantagem é que ele, diferente da maioria dos métodos do Swing, é thread-safe.

jeloy

Resolvido.

Muito obrigado pessoal pela atenção ;D

problemas as vezes simples sempre pegam pra quem ta começando.

ficou assim:

public class ReadTxt {
	String caminho;
	String arquivo;
	String sufixo;
	String ler = caminho + arquivo + sufixo;
	JFrame janela = new JFrame();
	JPanel painel = new JPanel();
	JTextArea texto = new JTextArea(40, 10);
	String str;
	String text = "";
	JScrollPane scroll = new JScrollPane();

	public ReadTxt(String caminho) throws IOException {
		BufferedReader in = null;  
            try {  
                 in = new BufferedReader(new FileReader(caminho));  
                 
                 while ( (str = in.readLine()) != null ) {  
                	 text += "\n"+str;
                 }
                	janela.setTitle(caminho);
             		janela.setSize(700, 600);
             		janela.add(painel);
             		painel.add(texto);
             		texto.setSize(600,900);
             		texto.setText(text);
             		janela.setVisible(true);
             		scroll.setViewportView(painel);
             		janela.add(scroll);
             		scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
             		 
                	System.out.println( text );  
                	
                   
              } catch (IOException e) {  
               e.printStackTrace();  
              }finally{  
               if( in != null ){  
                  in.close();  
               }  
              }
	}
		
}

funcionou perfeitamente…

vou testar com StringBuilder agora…

valeu mesmo pessoal…

depois eu posto o aplicativo aqui…

Criado 6 de janeiro de 2011
Ultima resposta 6 de jan. de 2011
Respostas 9
Participantes 5