Java: Using ActionListener, I need to get user input from a Text Field and use it, I'm having problems

20,809

If I understand correctly, you would like to append the text entered in the textfield to the output text area when the user presses Enter in the text field.

When Enter is pressed, the text field fires an action event. You listen to this event in your class. So, at this moment, you just need to append the value to the text area.

Swing is event-based:

public void actionPerformed(ActionEvent event) {
    String inputString = input.getText() ;
    output.append(inputString);
    input.setText("");
}

The code in the constructor is only executed at execution time. So getting the value of the text fields will of course return an empty string, since at construction time, the text field is not even visible yet.

EDIT : to do what you want, just have the following:

public void actionPerformed(ActionEvent event) {
    String inputString = input.getText() ;
    printOutcome(inputString);
    input.setText("");
}

private void printOutcome(String input) {
    char switchvariable = ' ';
    if (input.indexOf("hide") != -1) {
        switchvariable = 'b' ;
    }
    if ((input.indexOf("exit") != -1 ) || (input.indexOf("leave") != -1) || (input.indexOf("out") != -1)) {
        switchvariable = 'a';
    }
    if ((input.indexOf("exit") == -1) && (input.indexOf("hide") == -1) && (input.indexOf("leave") == -1) && (input.indexOf("out") == -1)) {
        switchvariable= 'c';
    }
    String outcome = "" ;
    switch (switchvariable) {
        case 'a' : 
            outcome = "You exit the tavern to be discovered by\na group of bandits!\n"; 
            break;
        case 'b' : 
            outcome = "You hide behind the bar for 10 minutes until\nyou can no longer hear the group." ; 
            break ;
        case 'c' : 
            outcome = "You must choose between the two given options, exit the tavern, or hide."; 
            break;
    }
    System.out.println(outcome);
}

This method is way too complex, though. There is no point in using an if clause to set a char variable, and then a switch over this char variable. And your if clauses should also be cleaned up.

Share:
20,809
user1913822
Author by

user1913822

Updated on December 19, 2020

Comments

  • user1913822
    user1913822 over 3 years

    so what I need to do is use a JTextField to get user input in the form of a String, whilst I can do this part, I'm having trouble getting the String from the method to analyse it elsewhere in the program, here is what I have so far:

     import javax.swing.* ;
     import java.awt.event.* ;
     import java.util.* ;
     class Games extends JFrame implements ActionListener
    {
      JPanel pnl = new JPanel() ;
      JTextField input = new JTextField(38) ;
      JTextArea output = new JTextArea(6, 37) ;
      JScrollPane pane = new JScrollPane(output) ;
      String inputString ;
    
    public Games()
    {
        super("Text Based RPG") ;
        setSize(600,200) ;
        setDefaultCloseOperation(EXIT_ON_CLOSE) ;
        output.setLineWrap(true) ;
        output.setWrapStyleWord(true) ;
        pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS) ;
        output.setEditable(false) ;
        pane.getVerticalScrollBar().setValue(100); //scrollbar always at bottom
        input.requestFocus() ;
    
        /*Edit: Should I call for the input string here, e.g. output.append(inputString)
         i get the compilation error message:
        Games.java:29: error: cannot find symbol
        output.append(inputString) ;
                      ^
        symbol:   variable inputString
        location: class Games
        */
    
        add(pnl) ;
        pnl.add(pane) ;
        pnl.add(input) ;
    
        input.addActionListener(this) ;
    
        setVisible(true) ;
    }
    
    public void actionPerformed(ActionEvent event) 
    {
        inputString = input.getText() ;
        input.setText("") ;
    }         
    /*The string i need to analyse is inputString, but I cannot, get it out of this method
      any help you guys can give me would be greatly appreciated. */
    
    public static void main(String[] args) 
    {
        Games gui = new Games() ;
    }
    }
    
    **********************************
        try
        {
            a = reader.readLine() ;
        }
        catch (IOException e ) 
        {
            System.out.println("An Input Error Has Occured") ;
        }
        if (a.indexOf("hide") != -1 ) switchvariable = 'b' ;
        if  ((a.indexOf("exit") != -1 ) || (a.indexOf("leave") != -1) || (a.indexOf("out") != -1)) switchvariable = 'a' ;
        if ((a.indexOf("exit") == -1) && (a.indexOf("hide") == -1) && (a.indexOf("leave") == -1) && (a.indexOf("out") == -1)) switchvariable= 'c' ;
        String outcome = "" ;
        switch (switchvariable) 
        {
        case 'a' : outcome = "You exit the tavern to be discovered by\na group of bandits!\n" ; i = -1 ; break ;
        case 'b' : outcome = "You hide behind the bar for 10 minutes until\nyou can no longer hear the group." ; i = -1 ; break ;
        case 'c' : outcome = "You must choose between the two given options, exit the tavern, or hide." ; break ; // the variable i will still be greater
        //than 1 so the loop will continue until you reach an agreeable option, which in this case is either hiding, or addressing the group of people
        }
        System.out.println(outcome) ;           
    

    What I would ideally like to do is use the textfield for user input, so what I need to do is put text in the output textarea, and then this should change according to the user input, an example of the code I would like to use is shown below the asterixes

  • user1913822
    user1913822 over 11 years
    Sorry I may have mis-lead you when I wrote in output.append(inputString), whilst the solution you gave is the right one, it's not what I'm looking for. I need to be able to pull the inputString out of the method to use it with an indexOf operator, if you know of a way to do this it would be greatly appreciated :)
  • user1913822
    user1913822 over 11 years
    The idea is to store data from the user in variables, but it's impossible to do this in the actionPerformed method because every time the user presses enter, everything appended in the method get's put in, which obviously is not the desired outcome.
  • JB Nizet
    JB Nizet over 11 years
    Call the indexOf() method from within the actionPerformed() method, or pass the inputString as an argument to another method that calls indexOf() on it. Storing the input string in a variable is a bad idea. If you don't understand, then edit your question and elaborate on what you really want to do.
  • user1913822
    user1913822 over 11 years
    OK I'll edit the question to say what I would like to do in full, thank you for your contribution.
  • user1913822
    user1913822 over 11 years
    You mentionned the method being too complex, are there any suggestions you could give to simplify what i'm trying to do? Also on the last line, this was from an earlier version, if I were trying to print the outcome into the output textarea, how would I change the line?
  • JB Nizet
    JB Nizet over 11 years
    Remove the switch completely, and initialize the outcome directly in the if clauses. And it seems you should simply use else if instead of negating the previous conditions.
  • user1913822
    user1913822 over 11 years
    I got the error message that method printOutcome in class Games cannot be applied to given types required: String, found: JTextField.
  • JB Nizet
    JB Nizet over 11 years
    It was a typo in my (now fixed) answer. You must of course pass inputString (the String which is in the text field when Enter is pressed) to the printOutcome() method. I really get the feeling that you don't understand how basic things like methods and arguments work. You should learn and practice with the basics before doing Swing development.
  • user1913822
    user1913822 over 11 years
    Yeah i pretty much read a book and am now trying to get familiar with everything by doing something worthwhile.
  • user1913822
    user1913822 over 11 years
    Althogh upon changing printOutcome(String input) to printOutcome(inputString), I now get the message error: <identifier> expected private void printOutcome(inputString) ^
  • JB Nizet
    JB Nizet over 11 years
    Re-read my answer. You didn't fix the code correctly. And this is basic stuff. You should really know how to declare a method and how to call a method before doing Swing.