Search code examples
javaswingjbuttonactionlistenerjtextfield

How do I get the String in a JTextField from an action of JButton?


For a while I have been trying to figure this out, searching online, finally decided to join just to figure this out. So my dilemma is this.

addActionListner(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
    //some code
}
});

What goes in some code that could actually pull from a JTextField (and for arguments sake let us call it myText)? Like how could I, if possible, call the ActionListner? so has when the button is clicked it actually performs the actionPeformed of the ActionListener in myText?


Solution

  • Add the action listener to the button and then retrieve myText's contents in the button's action listener. Hope it helps.

    Assuming your button is named something like "myButton":

    String someString = "";
    
    myButton.addActionListner(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
           //this will give you myText's contents. Do what you will with them.
           someString = myText.getText();
        }
    });
    

    Now you should be able to do whatever you want with the contents.