Pegar texto de um JTextArea

5 respostas
Evy

Gente, eu to tendo um problema ridiculo com o JTextArea.
Quando eu carrego minha aplicacao, ele le as configuracoes de um .properties pra um JTextArea.
Blz, ate ai funciona…
Tenho um botao de alterar, q quando o usuario muda o q ta nesse jTextArea, salva no .properties.
a parte do salvar eu sei q ta ok.
O problema eh q eu mudando o valor do textArea, apagando, sei la, ele nao ta mudando… ta continuando com o valor inicial.
o que pode ser?

5 Respostas

Mantu

Não entendi exatamento o quê não funciona…
Você diz:
“O problema eh q eu mudando o valor do textArea, apagando, sei la, ele nao ta mudando… ta continuando com o valor inicial.”
Q quem você está se referindo com o “ele”? “Ele” é o text area ou é o arquivo?
Qual das situações estão ocorrendo:
[list]1) Quando você muda o valor do text area, o arquivo não é atualizado? (Isto estaria em contradição com " Tenho um botao de alterar, q quando o usuario muda o q ta nesse jTextArea, salva no .properties.
a parte do salvar eu sei q ta ok.")[/list]
[list]2) Quando você muda o valor do text area e salva, o próprio text área “volta” ao ter o texto da última “salvada”?[/list]
[list]3) Será que na sua frase “O problema eh q eu mudando o valor do textArea,[…]”, ao invés de “textArea” você não queria se referir ao “.properties”? Ou seja, uma alteração no arquivo não é refletida no text area?[/list]

Aguardando sua resposta

Evy
"ele" eh o textfield. o codigo eh esse:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class JFrame_XML extends javax.swing.JFrame {

	public JFrame_XML(){
		initComponents();

	}

	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jLabel1 = new javax.swing.JLabel();
		jLFoto = new javax.swing.JTextField();
		JBFoto = new javax.swing.JButton();
		jLabel3 = new javax.swing.JLabel();
		jLTemplate = new javax.swing.JTextField();
		JBTemplate = new javax.swing.JButton();
		jLabel5 = new javax.swing.JLabel();
		jLCracha = new javax.swing.JTextField();
		jBCracha = new javax.swing.JButton();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		jLabel1.setText("local da foto: ");

		JBFoto.setText("Alterar");

		JBFoto.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				JBFotoActionPerformed(evt);
			}
		});

		jLabel3.setText("Local do template: ");



		JBTemplate.setText("Alterar");

		jLabel5.setText("Local do crachá: ");
		fis = null;
		fos = null;
		file = new File ("conf.properties");
		//file2 = new File("conf2.properties");
		props = new Properties();
		try {
			fis = new FileInputStream(file);
			props.load(fis);
			fis.close();
		}
		catch (IOException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		String cracha = props.getProperty("cracha");
		String templates = props.getProperty("templates");
		String fotos = props.getProperty("fotos");
		jLCracha.setText("");
		jLCracha.setText(cracha);
		jLTemplate.setText("");
		jLTemplate.setText(templates);
		jLFoto.setText("");
		jLFoto.setText(fotos);


		jBCracha.setText("Alterar");

		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(jLabel1)
								.addComponent(jLabel3)
								.addComponent(jLabel5))
								.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
										.addComponent(jLCracha, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
										.addComponent(jLTemplate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
										.addComponent(jLFoto, javax.swing.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE))
										.addGap(18, 18, 18)
										.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(JBFoto)
												.addComponent(JBTemplate)
												.addComponent(jBCracha))
												.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
		layout.setVerticalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(layout.createSequentialGroup()
						.addContainerGap()
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(jLabel1)
								.addComponent(jLFoto)
								.addComponent(JBFoto))
								.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
										.addComponent(jLTemplate)
										.addComponent(JBTemplate)
										.addComponent(jLabel3))
										.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
												.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(jLabel5)
														.addComponent(jLCracha))
														.addComponent(jBCracha))
														.addContainerGap(208, Short.MAX_VALUE))
		);

		pack();
	}

	public void JBFotoActionPerformed(java.awt.event.ActionEvent evt)
	{
		System.out.println(jLFoto.getText());
		jLFoto.selectAll();
		props.setProperty("fotos", jLFoto.getText());

		try {
			fos = new FileOutputStream(file);
			props.store(fos, "Configurações do arquivo conf.properties");
			fos.close();
		}
		catch (IOException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}

	public static void main(String args[])
	{
		JFrame_XML funciona = new JFrame_XML();
		funciona.initComponents();
		funciona.setVisible(true);

	}
	public Properties props;
	public File file;
	public FileInputStream fis;
	public JLabel jLabel1;
	public JTextField jLFoto;
	public JButton JBFoto;
	public JLabel jLabel3;
	public JTextField jLTemplate;
	public JButton JBTemplate;
	public JLabel jLabel5;
	public JTextField jLCracha;
	public JButton jBCracha;
	public FileOutputStream fos ;
//	public File file2;
}
o arquivo conf.properties (de onde eu leio as configuracoes) eh esse:
#Configurações do arquivo conf.properties
#Wed Mar 05 11:38:18 GMT-03:00 2008
templates=C\:\Documents and Settings\ctema\Desktop\templates
fotos=C\:\Documents and Settings\ctema\Desktop\fotos
cracha=C\:\Documents and Settings\ctema\Desktop\properties

o que nao ta tando certo é o seguinte:
eu acrescentei um listener ao primeiro botao (so pra teste mesmo)
os valores que estao nos campos sao os que estao sendo lidos do conf.properties.
O botao que tem o listener tem a funcao de pegar o que tem no text field e gravar no .properties.
Se eu apagar o valor do text field, e colocar alterar, o botao nao grava o valor que tinha no textfield, mas sim o valor que o text field tinha ANTES de eu alterar.
Entende?
Eu imagino que meu erro deve ser o mais ridiculo possivel, mas eu nao consigo achar :oops:

R

se vc debugar o codigo vc vai perceber que o field.getText() está vindo vazio…

vou dar mais uma olhada no codigo e ver o que descubro :wink:

mas já adianto que o erro é este

Mantu
Evy, eu testei aqui no meu e funcionou normal. Só fiz duas alterações no seu código: 1) Coloquei um if pra verificar se o arquivo properties existe. Se ele não existe, eu o crio. 2) Comentei, lá no main, a hora que você invoca o initComponents(), pois não há necessidade, uma vez que ela já é chamada pelo construtor da classe. Primeiro, escrevi "absdf" no campo de texto e cliquei no botão. Então abri o arquivo e tava lá certinho:
foto=absdf
Segundo, limpei o conteúdo do campo de texto e cliquei novamente no botão. Abri o arquivo e tava certinho novamente:
foto=
Terceiro, , escrevi "c:\temp" no campo de texto e cliquei no botão. Então abri o arquivo e tava lá certinho:
foto=c\:\temp
Aí vai o código que eu alterei (obs: Eu não uso net beans, por isso refiz a interface gráfica):
package br.com.mantu.help.guj.evy.propertiesManipulation;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class JFrame_XML extends javax.swing.JFrame {

	public JFrame_XML(){
		initComponents();

	}

	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jLabel1 = new javax.swing.JLabel();
		jLFoto = new javax.swing.JTextField();
		JBFoto = new javax.swing.JButton();
		jLabel3 = new javax.swing.JLabel();
		jLTemplate = new javax.swing.JTextField();
		JBTemplate = new javax.swing.JButton();
		jLabel5 = new javax.swing.JLabel();
		jLCracha = new javax.swing.JTextField();
		jBCracha = new javax.swing.JButton();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		jLabel1.setText("local da foto: ");

		JBFoto.setText("Alterar");

		JBFoto.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				JBFotoActionPerformed(evt);
			}
		});

		jLabel3.setText("Local do template: ");



		JBTemplate.setText("Alterar");

		jLabel5.setText("Local do crachá: ");
		fis = null;
		fos = null;
		file = new File ("conf.properties");
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		//file2 = new File("conf2.properties");
		props = new Properties();
		try {
			fis = new FileInputStream(file);
			props.load(fis);
			fis.close();
		}
		catch (IOException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		String cracha = props.getProperty("cracha");
		String templates = props.getProperty("templates");
		String fotos = props.getProperty("fotos");
		jLCracha.setText("");
		jLCracha.setText(cracha);
		jLTemplate.setText("");
		jLTemplate.setText(templates);
		jLFoto.setText("");
		jLFoto.setText(fotos);


		jBCracha.setText("Alterar");
		
		Container c = getContentPane();
		c.setLayout(new GridLayout(3, 3));
		c.add(jLabel1);
		c.add(jLFoto);
		c.add(JBFoto);
		c.add(jLabel3);
		c.add(jLTemplate);
		c.add(JBTemplate);
		c.add(jLabel5);
		c.add(jLCracha);
		c.add(jBCracha);
		setSize(600, 400);

//		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(jLabel1)
//								.addComponent(jLabel3)
//								.addComponent(jLabel5))
//								.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
//								.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
//										.addComponent(jLCracha, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
//										.addComponent(jLTemplate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
//										.addComponent(jLFoto, javax.swing.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE))
//										.addGap(18, 18, 18)
//										.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
//												.addComponent(JBFoto)
//												.addComponent(JBTemplate)
//												.addComponent(jBCracha))
//												.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
//		);
//		layout.setVerticalGroup(
//				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
//				.addGroup(layout.createSequentialGroup()
//						.addContainerGap()
//						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
//								.addComponent(jLabel1)
//								.addComponent(jLFoto)
//								.addComponent(JBFoto))
//								.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
//								.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
//										.addComponent(jLTemplate)
//										.addComponent(JBTemplate)
//										.addComponent(jLabel3))
//										.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
//										.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
//												.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
//														.addComponent(jLabel5)
//														.addComponent(jLCracha))
//														.addComponent(jBCracha))
//														.addContainerGap(208, Short.MAX_VALUE))
//		);
//
//		pack();
	}

	public void JBFotoActionPerformed(java.awt.event.ActionEvent evt)
	{
		System.out.println(jLFoto.getText());
		jLFoto.selectAll();
		props.setProperty("fotos", jLFoto.getText());

		try {
			fos = new FileOutputStream(file);
			props.store(fos, "Configurações do arquivo conf.properties");
			fos.close();
		}
		catch (IOException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}

	public static void main(String args[])
	{
		JFrame_XML funciona = new JFrame_XML();
//		funciona.initComponents();
		funciona.setVisible(true);

	}
	public Properties props;
	public File file;
	public FileInputStream fis;
	public JLabel jLabel1;
	public JTextField jLFoto;
	public JButton JBFoto;
	public JLabel jLabel3;
	public JTextField jLTemplate;
	public JButton JBTemplate;
	public JLabel jLabel5;
	public JTextField jLCracha;
	public JButton jBCracha;
	public FileOutputStream fos ;
//	public File file2;
}
Evy

obrigada Mantu…
Acho q o erro estava no initComponents neh?
Agora deu certo. :smiley:

Criado 5 de março de 2008
Ultima resposta 6 de mar. de 2008
Respostas 5
Participantes 3