Search code examples
javaeclipsemethodsusing

Calling String from another method - Java


I am trying to use this String called "username" from another method, but I can't seem to figure out what to do.

I have this bit of code right here, which assigns a text field's entry to a variable, but I can't seem to use this variable in another method

        //Configuring content pane
    JFormattedTextField formattedTextField = new JFormattedTextField();
    formattedTextField.setBounds(129, 36, 120, 20);
    UsernameFrame.getContentPane().add(formattedTextField);
    UsernameFrame.setVisible(true);

    //Assigning text field entry to variable
    String username = formattedTextField.getText();

Now, I am trying to use this variable in the method pasted below, but I don't know what I am missing..

            public void actionPerformed(ActionEvent e){
            if(username.length() < 5){

            }
            //Execute when the button is pressed
            System.out.println("The button has been pressed");
        }

This is probably something really simple I am missing, thanks for your help guys.

(full code)

http://pastebin.com/RMszazd4


Solution

  • Declare username right after your class declaration like this:

    public class App {
        private String username;
        public static void main(String[] args) {
            ...
        }
        ...
    }