0

I have a problem whilst trying to output a word from my array list into a text field on screen. Whenever I run the program and type a couple of words into the inbox field and click the analyse button, nothing gets outputted, any ideas?

import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Iterator;

public class SApplet extends Applet implements ActionListener {
TextField input,output;
Label label1;
Button b1, b2;
JLabel lbl;
String Word1;
String wordArrayList[];

public void init(){
    label1 = new Label("Please enter your text: ");
    add(label1);
    label1.setBackground(Color.orange);
    label1.setForeground(Color.black);
    input = new TextField(20);
    add(input);
    output = new TextField(20);
    add(output);
    b1 = new Button("Analyze");
    b2 = new Button("Reset");
    add(b1);
    add(b2);
    b1.addActionListener(this);
    b2.addActionListener(this);
    setBackground(Color.orange);
}

public void actionPerformed(ActionEvent e){
    try{
        String a = null;
        ArrayList<String> wordArrayList = new ArrayList<String>();
        if (e.getSource()== b1)
        {       
            Word1 = input.getText();
        for(String word : Word1.split(" ")) {
            wordArrayList.add(word); 
        }

        Iterator<String> word = wordArrayList.iterator();
        if (word.hasNext()) {
//              output.setText(word.next());
//              System.out.println(word.next());
            a += word.next();
        }

        while (word.hasNext()) {
            a += ", " + word.next();

            output.setText(a);
//              System.out.println(a);
        }
        }

        if(e.getSource() == b2)
            input.setText("");
        output.setText("");
    }
    catch(NumberFormatException a){
        lbl.setForeground(Color.red);
        lbl.setText("Invalid Entry!");
    }
}  
}

2 Answers 2

4

Your problem is here.

if(e.getSource() == b2)
    input.setText("");
output.setText("");

You probably intended to write this.

if(e.getSource() == b2) {
    input.setText("");
    output.setText("");
}

But because you left out the curly braces, blanking out output happens every time this method runs, not just if the button that triggered the event is b2.

Sign up to request clarification or add additional context in comments.

Comments

4

Enclose your if statements in braces

if (e.getSource() == b2) {
   input.setText("");
   output.setText("");
}

otherwise the second statement will always be executed in the ActionListener

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.