开发者

How do i connect jbutton to jtextfield?

开发者 https://www.devze.com 2023-03-09 17:41 出处:网络
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 c开发者_开发百科alculator.You can add an ActionListener to your bu

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 c开发者_开发百科alculator.


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");
    }
});


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();
        }
    });


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消