0

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();
  }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 3
    Take a look at [How to use Actions](https://docs.oracle.com/javase/tutorial/uiswing/misc/action.html) tutorial, and while you're on it follow the [Java naming conventions](https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html). Basically add an `ActionListener` to your `mybutton`, and when that happens, do a `System.out.println(textField1.getText())`. Also take a look at [Extends JFrame vs creating an object](https://stackoverflow.com/questions/22003802/extends-jframe-vs-creating-it-inside-the-program) – Frakcool Apr 22 '21 at 21:59
  • *"I am supposed to.."* It's a fairly unusual requirement to want a combination of GUI & command line/console input/output. The advice is usually to stick with or the other. – Andrew Thompson Apr 23 '21 at 07:07

1 Answers1

2

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()));
oktaykcr
  • 346
  • 6
  • 12