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にアクションを追加し、Enterキー用にInputMapを設定してみてください。

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

これはあなたに多くの問題を引き起こすでしょう。まず、アプレットがクライアントマシンから読み取るためのアクセス権を持っていない可能性が高いため、セキュリティ例外が発生する可能性があります。次に、前のステートメントで示唆されているように、ファイルがクライアントマシンに存在する可能性は低いです。

このリソースをアプリケーションのJar内に埋め込み、それを使用getClass().getResource("...")してアクセスする必要があります。これによりURL、が返されます。これを使用して、スキャナーで使用できるにURL#openConnectionアクセスできます。InputStream

于 2012-11-02T04:43:03.733 に答える
0

私もJavaの初心者ですが、それJTextfieldは1行のエントリにすぎないことがわかりました。複数行のエントリが必要な場合は、JTextArea代わりに使用する必要があります。

お役に立てれば :)

于 2013-01-29T11:28:07.513 に答える