سؤال

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!");
    }
}  
}
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top