BraginiNI
BraginiNI

Reputation: 586

using java swing

I need to put a value in to my class from UI (Swing) and then start my method by clicking a button. What should I do?

Upvotes: 0

Views: 279

Answers (3)

thewhitetulip
thewhitetulip

Reputation: 3309

Swing is just the user interface you provide to to your app. it works like this.... you have buttons, panels and all the stuff you need for providing a proper interface, which means if you need to take text input you'll put textfield or textArea in your UI

swing applications are based on events, thats the basic difference between console based and window based applications, a console based application is sequential it compiles and then executes code sequentially it has no regard of how you interact with it.

a swing application on the other hand is event based, until any event is fired and caught it won't do anything, in java you just handle the event, which means what happens after an event occurs is decided by the programmer.

suppose there is a button click event fires and there is a listener attached to the element then the actionPerformed function gets called and it is executed

suppose you want to get the user name from the app

 JButton btnSubmit = new JButton("Submit");
 JTextField txtName = new JTextField("", 4);

btnSubmit.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent e){
     String name = txtName.getText();//see below for explanation
     printInfo();//write the function call statements here if you want them to be executed when button is clicked

}
});

whenever button is clicked or more generally any event occurs on the button then it creates a string object in the string pool and assigns to it the value of the text field at the time when the button was clicked

Upvotes: 0

saethi
saethi

Reputation: 53

Here's a super simple example of a text field and a button that, when clicked, will get the text value then you can all the method you'd like to pass that value to.

public class ButtonExample extends JPanel
{
    private JTextField _text;

    public ButtonExample()
    {
        _text = new JTextField();

        setLayout( new BorderLayout() );
        add( _text, BorderLayout.NORTH );
        add( new JButton( new CaptureTextAction() ), BorderLayout.SOUTH );
    }

    private class CaptureTextAction extends AbstractAction
    {
        private CaptureTextAction()
        {
            super( "Click Me" );
        }

        @Override
        public void actionPerformed( ActionEvent ae )
        {
            String textToCapture = _text.getText();

            // do something interesting with the text
        }
    }
}

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240996

Upvotes: 2

Related Questions