Charles
Charles

Reputation: 1

How do i connect jbutton to jtextfield?

how do i write the action that will enable my textfield and button to interact, using netbeans IDE, i'm trying to write a scientific calculator.

Upvotes: 0

Views: 9193

Answers (3)

ama291
ama291

Reputation: 70

When a button is pressed on a calculator, the field at the top isn't just changed to the desired value when a button is pressed; the value is added to the end of the current text in the field.

final JTextField text = new JTextField("1", 10);
    final JButton button  = new JButton("Button");
    button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            text.setText(text.getText() + "1"); //value in the quotes is added
        }
    });

This solution uses an inner class to create an action listener for the button. When the button is pressed, it sets the text in the text box to the current text plus the value in the quotes.

Upvotes: 0

Darren Burgess
Darren Burgess

Reputation: 4312

You Should add an action listener which will allow you to assign your desired method to the action performed method. For example when a button is clicked you could take the value entered into your JTextfield and convert it to a string.

 submit.addActionListener(new ActionListener()
        {
        public void actionPerformed(ActionEvent e)
        {
           newString = textfieldname.getText();
        }
    });

Upvotes: 0

dogbane
dogbane

Reputation: 274532

You can add an ActionListener to your button which will be called when the button is pressed. You can then change the text in the text field.

final JTextField tf = new JTextField();
final JButton button  = new JButton("BUTTON");
button.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e) {
        tf.setText("123");
    }
});

Upvotes: 1

Related Questions