【问题标题】:pressing ENTER key do not work for JTextField in applet按下 ENTER 键不适用于小程序中的 JTextField
【发布时间】:2012-10-22 17:08:27
【问题描述】:

我在带有 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;
}

非常感谢您的帮助。

【问题讨论】:

  • 对我来说很好用,还有更多来源吗?

标签: java swing actionlistener jtextfield japplet


【解决方案1】:

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

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

该字段必须具有焦点。

【讨论】:

  • 对不起,我是个菜鸟,但我应该把代码放在 public void init() 中吗?而且它“无法解析 KeyStroke”。
  • @user1793092 import javax.swing.KeyStroke;
【解决方案2】:

我也是 Java 新手,但发现 JTextfield 只是一个单行条目。 如果需要多行条目,则需要使用 JTextArea

希望这会有所帮助:)

【讨论】:

    【解决方案3】:

    这似乎对我有用....

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

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

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

    【讨论】:

    • 它仍然对我不起作用。如果我取出 ProcessString();和答案();函数,然后代码工作。但是,如果我将它们放在同一个 JApplet 类中,则它不起作用。即使我取出函数并将它们放在一个单独的类中(并调用类函数),它仍然不起作用。所以基本上,调用这些函数是如何使它无法在 .html 小程序中工作的。
    • S,我们需要查看 ProcessString 和 Answer 方法以了解更多信息
    • 有点乱,但就是这样。我试图在这些函数中读取文本文件和/或写入文本文件。我贴在最后。
    • 非常感谢。我在同一目录中有文件。但看起来我需要回到绘图板上学习一些基础知识。我是从本地应用程序迁移过来的,所以我需要了解 Web 应用程序。
    猜你喜欢
    • 2017-04-18
    • 2018-08-18
    • 2016-01-03
    • 2020-09-10
    • 2021-07-22
    • 2018-08-05
    • 2011-12-14
    • 1970-01-01
    • 2011-12-18
    相关资源
    最近更新 更多