whiteshadow
whiteshadow

Reputation: 1

How to make Text Field in GUI submit text into Console?

I am not sure how to make this all work together but I am supposed to make the text field display the text typed but only when we press submit. It is supposed to display the text in the console. So I need some help adding onto this to finish the code.

    import java.awt.*;
    import javax.swing.*;

    public class testExample1 extends JFrame {
      JTextField textField1;
      JButton mybutton;

    public testExample1() {
      setSize(300, 100);
      setTitle("Text Action");
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLayout(new FlowLayout());
    
      textField1 = new JTextField(10);
      mybutton = new JButton("Submit");
    
      add(textField1);
      add(mybutton);
    
      setVisible(true);
     
      System.out.println()
   }
    public static void main(String args[]) {
          new testExample1();
  }
}

Upvotes: 0

Views: 1099

Answers (1)

oktaykcr
oktaykcr

Reputation: 376

You need to add an ActionListener to your submit button.

mybutton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
         System.out.println(textField1.getText());
    }
});

Or

With Java 8 Lambda expressions:

mybutton.addActionListener(e -> System.out.println(textField1.getText()));

Upvotes: 2

Related Questions