1

我在带有 ActionListener 的 JApplet 中有一个 JTextField。我使用 Eclipse 编译它,它工作正常。但是,当我尝试使用小程序将其加载到 .html 文件中时,当我按下 JTextField 时,它不会注册/识别 ENTER 键。ActionListener 似乎不起作用。我用了:

public void init() {
    textField = new JTextField(20);
    textField.setText("Enter your question here.");
    textField.selectAll();
    textField.addActionListener(this);

    textArea = new JTextArea(10, 20);
    textArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(textArea,
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    // Add Components to the Applet.
    GridBagLayout gridBag = new GridBagLayout();
    Container contentPane = getContentPane();
    contentPane.setLayout(gridBag);
    GridBagConstraints c = new GridBagConstraints();
    c.gridwidth = GridBagConstraints.REMAINDER;

    c.fill = GridBagConstraints.HORIZONTAL;
    gridBag.setConstraints(textField, c);
    contentPane.add(textField);

    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.weighty = 1.0;
    gridBag.setConstraints(scrollPane, c);

    contentPane.add(scrollPane);

    newline = System.getProperty("line.separator");
}

public void actionPerformed(ActionEvent event) {
    String text = textField.getText();
    String question = "";
    String answer = "";

    question = textField.getText();
    question = ProcessString(question);
    answer = Answer(question);
    textArea.append(text + newline);
    textArea.append(answer + newline);
    textField.selectAll();
}

static String noAnswer;
static boolean knowAnswer = true;

// process the question string, take out non-ACSII characters, spaces, to
// lower space
public String ProcessString(String question) {
    question = question.toLowerCase();
    String[] words = question.split("\\s+");

    question = "";
    for (int wordCount = 0; wordCount < words.length; wordCount++) {
        words[wordCount] = words[wordCount].replaceAll("[^A-Za-z]", "");
        if (wordCount != words.length - 1)
            question = question + words[wordCount] + " ";
        else
            question = question + words[wordCount];
        // System.out.println(words[wordCount]);
    }
    return question;
}

public String Answer(String question) {

    String answer = "";

    /*
      if the database know the answer (did not not know), then return the
      answer. if the database does not know the answer, then recover the
      answer in database.
    */
    if (knowAnswer == true) {
        // open the database file and search if questions matches any one in
        // the
        // database
        Scanner sc = null;
        try {
            sc = new Scanner(new File("database.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        int answerFrequency = 0;

        boolean matchFound = false;

        while (sc.hasNext()) {

            int questionCount = sc.nextInt();
            String line = sc.nextLine();

            String[] databaseLine = line.split("\\s+");
            String databaseQuestion = "";
            String databaseAnswer = "";

            // collect words for database questions
            for (int wordCount = 1; wordCount <= questionCount; wordCount++) {
                if (wordCount != questionCount)
                    databaseQuestion = databaseQuestion
                            + databaseLine[wordCount] + " ";
                else
                    databaseQuestion = databaseQuestion
                            + databaseLine[wordCount];
            }

            // collect words for database answer
            for (int wordCount = questionCount + 2; wordCount < databaseLine.length; wordCount++) {
                databaseAnswer = databaseAnswer + databaseLine[wordCount]
                        + " ";
            }

            // if the question is found in database, print answer
            if (question.equals(databaseQuestion)) {
                matchFound = true;

                // the current answer is more frequency than the previous
                // found
                // answer, reassign the current answer the find answer
                if (answerFrequency < Integer
                        .parseInt(databaseLine[questionCount + 1])) {
                    answerFrequency = Integer
                            .parseInt(databaseLine[questionCount + 1]);
                    answer = databaseAnswer;
                }
            }
        }

        if (matchFound == true) {
            // System.out.println(answer);
            knowAnswer = true;
        } else {
            // System.out.println("I don't know what you mean. How should I answer your question?");
            knowAnswer = false;
            noAnswer = question;
            answer = "I don't know how to respond. How should I answer that?";
        }

        sc.close();
    } else if (knowAnswer == false) {
        String[] word = noAnswer.split(" ");

        BufferedWriter writer = null;
        answer = question;
        try {
            writer = new BufferedWriter(
                    new FileWriter("database.txt", true));
            writer.newLine();
            writer.write(word.length + " " + noAnswer + " 1 " + answer);
        } catch (IOException e) {
        } finally {
            try {
                if (writer != null)
                    writer.close();
            } catch (IOException e) {
                System.out.println("Cannot write to file");
            }
        }
        answer = "I got that.";
        knowAnswer = true;
    }
    return answer;
}

非常感谢您的帮助。

4

3 回答 3

1

尝试向 ActionMap 添加一个 Action 并将 InputMap 设置为 ENTER 键。

textField.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter" );
textField.getActionMap().put("enter", new AbstractAction() {...} );

该领域必须有重点。

于 2012-11-02T02:52:40.123 回答
1

这似乎对我有用....

public class TestApplet04 extends JApplet implements ActionListener {

    private JTextField textField;
    private JTextArea textArea;
    private String newline;

    public void init() {
        textField = new JTextField(20);
        textField.setText("Enter your question here.");
        textField.selectAll();
        textField.addActionListener(this);

        textArea = new JTextArea(10, 20);
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textArea,
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        // Add Components to the Applet.
        GridBagLayout gridBag = new GridBagLayout();
        Container contentPane = getContentPane();
        contentPane.setLayout(gridBag);
        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;

        c.fill = GridBagConstraints.HORIZONTAL;
        gridBag.setConstraints(textField, c);
        contentPane.add(textField);

        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1.0;
        c.weighty = 1.0;
        gridBag.setConstraints(scrollPane, c);

        contentPane.add(scrollPane);

        newline = System.getProperty("line.separator");
    }

    public void actionPerformed(ActionEvent event) {
        String text = textField.getText();
        String question = "";
        String answer = "";

        question = textField.getText();
//        question = ProcessString(question);
//        answer = Answer(question);
        textArea.append(text + newline);
        textArea.append(answer + newline);
        textField.selectAll();
    }
}

反馈后更新

这是你的主要问题...

sc = new Scanner(new File("database.txt"));

这会给你带来很多问题。首先,小程序可能没有从客户端机器读取的访问权限,因此您可能会遇到安全异常。其次,正如前面的陈述可能暗示的那样,文件 ins 不太可能存在于客户端计算机上。

您需要将此资源嵌入到应用程序的 Jar 中并用于getClass().getResource("...")访问它。这将返回 a URL,您可以使用它URL#openConnection来访问InputStream可以在扫描仪中使用的 a 。

于 2012-11-02T04:43:03.733 回答
0

我也是 Java 的新手,但发现这JTextfield只是一个单行条目。如果您想要一个多行条目,则需要使用 aJTextArea代替。

希望这可以帮助 :)

于 2013-01-29T11:28:07.513 回答