Como posso puxar informações de um outro frame?

Boa noite Pessoal!

Estou com um problema… Eu gostaria de fazer um botão de um segundo frame que eu fiz, mostrar o resultado de um JTextField do primeiro frame.
PRIMEIRO FRAME

package N2;
public class testn3 implements ActionListener {
JTextField t;
JPanel p1;
JPanel p2;
JPanel p3;
JLabel lb;
JButton b;
JFrame frame;
JMenuBar menuBar;
JMenu menu1;
JMenuItem tuto;
JMenuItem sair;

private void montaFormulario() {
	menuBar = new JMenuBar();
	menu1 = new JMenu("Opções");
	menuBar.add(menu1);
	tuto = new JMenuItem("Tutorial", new ImageIcon("img/tuto2.png"));
	sair = new JMenuItem("Sair", new ImageIcon("img/sair2.png"));
	menu1.add(tuto);
	menu1.add(sair);
	
	
	frame = new JFrame("Criptotexto");
	frame.setJMenuBar(menuBar);
	
	
	
	 p1 = new JPanel();
	 p2 = new JPanel();
	 p3 = new JPanel();
	 lb = new JLabel("Digite o Texto:");
	 lb.setText( "<html><font color=FF0000>Digite o Texto: </font><font color=00FF00>");
	 t = new JTextField(10);
	 Icon icone = new ImageIcon("img/pad.png");
	 b = new JButton("Descriptografar", icone);
	 b.setForeground(Color.BLUE);
	 t.setForeground(Color.WHITE);
	 b.addActionListener(this);
	 tuto.addActionListener(this);
	 sair.addActionListener(this);
	 Font fonte = new Font("Courier New", Font.BOLD,20);
	 lb.setFont(fonte);
	
	

	p1.add(lb);
	p2.add(t);
	p3.add(b);
	p3.setBackground(Color.green);
	p2.setBackground(Color.green);
	p1.setBackground(Color.green);
	t.setBackground(Color.black);
	
	
	
	
	frame.add(p1, BorderLayout.NORTH);	frame.add(p2, BorderLayout.CENTER);	frame.add(p3, BorderLayout.SOUTH);		
	
	frame.setBounds(100, 100, 250, 180);
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	frame.setVisible(true);	
	
}





public void actionPerformed(ActionEvent e) {
	if(e.getSource() == tuto) {
		JOptionPane.showMessageDialog(null,"Exemplos de Entrada:\n\n\n1) NoTApasCAL\r\n"
				+ "2) atEQUEatabELATERMINE\r\n"
				+ "3) zoEIrrRRRRa");
	}
	else if(e.getSource() == sair){
		System.exit(0);
	}

	else {
		new SecondFrame();

// int j;
// String entrada;
// String saida= “”;
// entrada = t.getText();
// for(j=entrada.length()-1; j>=0; j–) {
// if(entrada.charAt(j) >= 96)
// saida += entrada.charAt(j);
// }
// if(saida == “”) {
// JOptionPane.showMessageDialog(null, “Digite o Texto!”,“Error!”, JOptionPane.ERROR_MESSAGE);
// }
// else
// JOptionPane.showMessageDialog(null, saida,“Descriptografado Com Sucesso!”, 3);

}
}

public static void main(String[] args) {
	try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        System.err.println(ex);
    } catch (InstantiationException ex) {
    	System.err.println(ex);
    } catch (IllegalAccessException ex) {
    	System.err.println(ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
    	System.err.println(ex);
    }
	new testn3().montaFormulario();
	

}

}
image

SEGUNDO FRAME

public class SecondFrame {
JFrame f = new JFrame(“Sucesso!”);
JPanel p = new JPanel();
JPanel p2 = new JPanel();
JLabel lb = new JLabel(“Texto Descriptografado Com Sucesso!”);
JButton b = new JButton(“Mostrar”);

public SecondFrame() {
	
	p.add(b);
	p2.add(lb);
	f.add(p, BorderLayout.CENTER);
	f.add(p2, BorderLayout.NORTH);
	f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	f.pack();
	f.setVisible(true);
}

}
image

Galera, no meu caso quando eu clico no botão descriptografar ele mostra esse segundo frame… e eu quero a partir deste segundo botão(mostrar), o resultado que está como comentário ali… no frame 1… no caso eu quero ao menos pegar o tesxfield do frame 1 pra fazer …

Você deve tornar a várivavel que você quer acessar o valor como public static então você poderá instanciar ela em outra classe e pegar o valor da variável.

public static TextField texto;
SuaClasse.texto...

Não mesmo.
A palavra static serve para você criar membros de CLASSE ao invés de membros de INSTÂNCIA.

Qual a solução do problema então? Lembrando q quem está com dúvida não sou eu, apenas apresentei uma solução. É um tópico de dúvida não de correção alheia…Obrigado pelo toque mesmo assim.

1 curtida

Como é que objetos trocam mensagens entre si?
R: Através de métodos.

Existem N formas de implementar isso.

Geralmente quando uma classe aguarda uma mensagem de outra, se implementa uma estrutura de listeners para isso.

Mas nesse exemplo, o mais fácil é a segunda tela dele ter uma referência para a primeira e aí ter acesso aos membros públicos dela.

Exemplo:

Classe FirstFrame:

package n2;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.WindowAdapter;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;

@SuppressWarnings("serial")
public class FirstFrame extends JFrame {

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            FirstFrame firstFrame = new FirstFrame();
            firstFrame.setVisible(true);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    private JTextField t;
    private JPanel p1;
    private JPanel p2;
    private JPanel p3;
    private JLabel lb;
    private JButton b;
    private JMenuBar menuBar;
    private JMenu menu1;
    private JMenuItem tuto;
    private JMenuItem sair;

    public FirstFrame() {
        super("Criptotexto");
        menuBar = new JMenuBar();
        menu1 = new JMenu("Opções");
        menuBar.add(menu1);
        tuto = new JMenuItem("Tutorial", new ImageIcon("img/tuto2.png"));
        sair = new JMenuItem("Sair", new ImageIcon("img/sair2.png"));
        menu1.add(tuto);
        menu1.add(sair);

        setJMenuBar(menuBar);

        p1 = new JPanel();
        p2 = new JPanel();
        p3 = new JPanel();
        lb = new JLabel("Digite o Texto:");
        lb.setText("<html><font color=FF0000>Digite o Texto: </font><font color=00FF00>");
        t = new JTextField(10);
        Icon icone = new ImageIcon("img/pad.png");
        b = new JButton("Descriptografar", icone);
        b.setForeground(Color.BLUE);
        t.setForeground(Color.WHITE);
        b.addActionListener(event -> descriptografar());
        tuto.addActionListener(event -> exemplos());
        sair.addActionListener(event -> sair());
        Font fonte = new Font("Courier New", Font.BOLD, 20);
        lb.setFont(fonte);

        p1.add(lb);
        p2.add(t);
        p3.add(b);
        p3.setBackground(Color.green);
        p2.setBackground(Color.green);
        p1.setBackground(Color.green);
        t.setBackground(Color.black);

        add(p1, BorderLayout.NORTH);
        add(p2, BorderLayout.CENTER);
        add(p3, BorderLayout.SOUTH);

        setBounds(100, 100, 250, 180);
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        setLocationRelativeTo(null);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent e) {
                sair();
            };
        });
    }

    public JTextField getTextField() {
        return t;
    }

    private void descriptografar() {
        SecondFrame secondFrame = new SecondFrame(this);
        secondFrame.setVisible(true);
    }

    private void exemplos() {
        JOptionPane.showMessageDialog(this, "Exemplos de Entrada:\n\n\n1) NoTApasCAL\r\n" + "2) atEQUEatabELATERMINE\r\n" + "3) zoEIrrRRRRa");
    }

    private void sair() {
        int option = JOptionPane.showConfirmDialog(this, "Deseja realmente sair?", "Confirmação", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (option == JOptionPane.YES_OPTION) {
            System.exit(0);
        }
    }
}

Classe SecondFrame:

package n2;

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

@SuppressWarnings("serial")
public class SecondFrame extends JFrame {

    private JPanel p = new JPanel();
    private JPanel p2 = new JPanel();
    private JLabel lb = new JLabel("Texto Descriptografado Com Sucesso!");
    private JButton b = new JButton("Mostrar");
    private FirstFrame firstFrame;

    public SecondFrame(FirstFrame firstFrame) {
        super("Sucesso");
        this.firstFrame = firstFrame;

        b.addActionListener(event -> mostrar());
        p.add(b);
        p2.add(lb);
        add(p, BorderLayout.CENTER);
        add(p2, BorderLayout.NORTH);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        pack();
        setLocationRelativeTo(firstFrame);
    }

    private void mostrar() {
        JTextField textField = firstFrame.getTextField();

        String entrada = textField.getText();
        String saida = "";
        for (int j = entrada.length() - 1; j >= 0; j--) {
            if (entrada.charAt(j) >= 96)
                saida += entrada.charAt(j);
        }
        if ("".equals(saida)) {
            JOptionPane.showMessageDialog(this, "Digite o Texto!", "Erro", JOptionPane.ERROR_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(this, saida, "Descriptografado Com Sucesso!", JOptionPane.INFORMATION_MESSAGE);
        }
    }
}
1 curtida

O que vejo faltando, são padrões de projeto. Um obsorver, poderia ajuda-lo

Sim, foi o que eu disse.
Listener e Observer são sinônimos.

1 curtida

Perdoe minha falta de atenção