Olá gente! Sou eu novamente…
Bom, é o seguinte:
Tenho uma classe que se chama Janela, e nela eu tenho um label e um botão, eu gostaria que quando o botão fosse clicado, ele executasse em uma outra classe que se chama Acesso, o método que se chama alteraLabel, para que este método possa executar o método setTexto da classe Janela.
Desculpem, Sei que esta confusa e meio sem sentido, pois eu poderia fazer isto direto na classe Janela, mas a idéia é realmente experimentar e aprender. Obrigado galera!
public class Janela implements ActionListener { //***classe Janela
private JFrame frmJanela;
private JLabel lblTeste;
private JButton btnTeste;
public void criaJanela() {
JFrame.setDefaultLookAndFeelDecorated(true);
frmJanela = new JFrame("");
frmJanela.setSize(130, 100);
frmJanela.setLocation(280, 280);
frmJanela.setLayout(null);
lblTeste = new JLabel("Teste de acesso");
lblTeste.setBounds(10, 10, 150, 20);
frmJanela.getContentPane().add(lblTeste);
btnTeste = new JButton("teste");
btnTeste.setBounds(10, 40, 100, 20);
btnTeste.addActionListener(this);
frmJanela.getContentPane().add(btnTeste);
frmJanela.setVisible(true);
}
/*
* Abaixo esta o método para alterar, mas não consigo alterar o texto
* pois sempre da erro.
*/
public void setTexto(String novoTexto){
this.lblTeste.setText(novoTexto);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == btnTeste){
Acesso executa = new Acesso();
executa.alteraLabel(); //***** Aqui eu tento executar o método alteraLabel
//da classe Acesso.
}
}
public static void main(String args[]){
Janela executa = new Janela();
executa.criaJanela();
}
}
//*** abaixo a classe acesso
public class Acesso {
public void alteraLabel(){
Janela nova = new Janela();
nova.setTexto("Alterado");
}
Bom dia boca,
Veja se este exemplo te ajuda ou se ai complicar um pouco mais… É que envolve bastante coisa neste exemplo. Pelo que senti no seu código você está iniciando em JAVA correto? procure pesquisar sobre os assuntos relacionados no exemplo abaixo. Qualquer coisa é só perguntar. São 3 arquivos ok?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class MeuFrame extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
private JTextArea t;
public MeuFrame(){
this.setSize(500,500);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
t = new JTextArea();
Font f = new Font("Arial",Font.ITALIC,32);
t.setForeground(Color.WHITE);
t.setBackground(Color.BLACK);
t.setFont(f);
this.getContentPane().add(t);
JPanel p = new JPanel();
JButton b = new JButton(Botoes.SAIR.getTexto());
b.addActionListener(this);
JButton b2 = new JButton(Botoes.MENSAGEM.getTexto());
b2.addActionListener(this);
p.add(b2);
p.add(b);
this.getContentPane().add(p,BorderLayout.SOUTH);
Tratamento.lerArquivo(t);
this.setVisible(true);
}
public static void main(String[] args) {
new MeuFrame();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equalsIgnoreCase(Botoes.MENSAGEM.getTexto()))
Tratamento.emiteMensagem();
else
Tratamento.gravarArquivo(t);
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class Tratamento {
public static void lerArquivo(JTextArea t){
try{
BufferedReader br = new BufferedReader(new FileReader(new File("C:/teste.txt")));
String str;
while ((str = br.readLine()) != null)
t.append(str+"\n");
br.close();
}catch(Exception e){
e.printStackTrace();
}
}
public static void gravarArquivo(JTextArea t){
try{
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(new File("C:/teste.txt"))));
pw.write(t.getText().replace("\n", "\r\n"));
pw.close();
System.exit(0);
}
catch(Exception e){
e.printStackTrace();
}
}
public static void emiteMensagem(){
JOptionPane.showMessageDialog(null,"Ola");
}
}
Veio, vc tem que passar o JLabel no parametro, já que vc que a outra classe altere o texto. Agora, como é só um teste, blz. Mas numca faça isso em uma aplicação real. Fica uma porcaria.
public void alteraLabel(JLabel jLabel, String texto){
jLabel.setText(texto);
}
Gilson, realmente sou iniciante, e senti pelo seu código que vc é pra lá de avançado rs… Adorei o exemplo que vc postou, e apesar de ser um pouco confuso pra mim ainda, já me ajudou bastante na parte de manipulação de arquivos.
Já o exemplo do nosso amigo Dantas, serviu como uma luva, pois estou tentando entender como funciona a passagem de parâmetros. Só não entendi se quando vc disse que ficaria uma porcaria em uma aplicação real, vc se referiu a lógica que eu estou utilizando(que é uma porcaria mesmo) ou a passagem daqueles parâmetros?