【问题标题】:Array List wont output. Java AppletArraylist 不会输出。 Java 小程序
【发布时间】:2014-02-10 00:00:00
【问题描述】:

我在尝试将数组列表中的单词输出到屏幕上的文本字段时遇到问题。每当我运行程序并在收件箱字段中输入几个单词并单击分析按钮时,什么都没有输出,有什么想法吗?

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!");
    }
}  
}

【问题讨论】:

    标签: java arrays list applet textfield


    【解决方案1】:

    你的问题就在这里。

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

    你可能打算写这个。

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

    但是由于您省略了花括号,因此每次运行此方法时都会将output 清空,而不仅仅是在触发事件的按钮是b2 时。

    【讨论】:

      【解决方案2】:

      将您的 if 语句括在大括号中

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

      否则第二条语句将始终在ActionListener中执行

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-31
        • 1970-01-01
        • 2011-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-05
        相关资源
        最近更新 更多