Show text typed in text field after button click

1

The code below I got from the internet is working for me. In main , it executes a form with the name to type and the ok button.

I wanted to run in main , right after the new MeuPrograma(); a System.out.println("##") where it displays the name that the guy typed there in the field of swing How do I do this?

public class MeuPrograma extends JFrame  {



public static JTextField text = new JTextField(10);

private static final long serialVersionUID = 1L;
    private JLabel labelNome;
    private JTextField textFieldNome;
    private JButton buttonOk;

    public MeuPrograma() {
        setTitle("Programa Swing1");
        setLayout(new FlowLayout());
        labelNome = new JLabel("Nome: ");
        textFieldNome = new JTextField(15);
        buttonOk = new JButton("OK");
        // --> adiciona os componentes a janela
        add(labelNome);
        add(textFieldNome);
        add(buttonOk);
        // --> ajusta o tamanho, a posicao e a acao ao fechar
        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        // --> mostra a janela
        setVisible(true);
    }



public static void main(String[] args)  {

    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        e.printStackTrace();
    }
    // --> cria um novo objeto do tipo Swing1
    // por causa da execucao multithreading da
    // API swing,isso deve ser feito dessa forma:
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new MeuPrograma();
        }
    });
    
asked by anonymous 15.01.2016 / 19:09

1 answer

3

To capture the value typed in a JTextFiled after the button is pressed, add a listener in JButton , using the actionPerformed ", something like this:

buttonOk.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
  String strTexto = textFieldNome.getText();
  //adicione o que quer fazer com o texto
 }
});

Because this is an invocation of anonymous class , to pass the value to the listener

15.01.2016 / 19:29