Kristopher Pacifico
Kristopher Pacifico

Reputation: 11

How can I connect my JButton to my JTextField to store the int I input into the JTextField?

I have created a simple GUI JFrame that has a textfield and button with their given action listeners. But I am trying to connect the textfield to the button so that whenever I have inputted a series of numbers into the text field and press the button, my code stores the series of numbers to a variable that I will use later on. How do I connect the two to start off with?

I have looked at other stackoverflow posts, but I cannot seem to find a solution.

   //textfield
   id = new JTextField(7);// accepts up to 7 characters    

   //buttons
   go = new JButton("Go");
   go.setBounds(100, 150, 140, 40);
   CL = new JButton("Cheap Lock");
   CL.setBounds(100,300,140,40);

   //JLabel that shows button has stored the input
   go1 = new JLabel();
   go1.setBounds(10, 160, 200, 100);


   //button action listener
   go.addActionListener(new ActionListener() {          
            @Override
            public void actionPerformed(ActionEvent arg0) {
                    go1.setText("Student ID has been submitted.");              
            }          
          });
   //textfield actionlistener
   id.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
         id.getText();
         }
         });
   }

Upvotes: 1

Views: 24

Answers (1)

Matt
Matt

Reputation: 2213

You've got an ActionListener on your button, which is a good start. You should write some logic to grab the text from the JTextField, parse it as you want and store it in a data structure (e.g. an ArrayList).

You don't seem to need the JTextField ActionListener right now - move the id.getText() call into the JButton ActionListener and store it in a variable.

//textfield
id = new JTextField(7);// accepts up to 7 characters    

//buttons
go = new JButton("Go");
go.setBounds(100, 150, 140, 40);
CL = new JButton("Cheap Lock");
CL.setBounds(100,300,140,40);

//JLabel that shows button has stored the input
go1 = new JLabel();
go1.setBounds(10, 160, 200, 100);


//button action listener
go.addActionListener(new ActionListener() {          
        @Override
        public void actionPerformed(ActionEvent arg0) {
                go1.setText("Student ID has been submitted.");
                String value = id.getText();
                // logic here - e.g. Integer.parseInt();            
        }          
});

Upvotes: 2

Related Questions