gpt4 book ai didi

java - DocumentListener 或 KeyListener

转载 作者:行者123 更新时间:2023-11-29 06:32:26 25 4
gpt4 key购买 nike

this question的评论中提到了并在 this question 的答案中应该使用 documentListenerdocumentFilter 而不是 keyListener。这是为什么?

在前几天我写的一个简单的 Hangman 游戏中,我做了类似下面的代码:

public class Hangman extends JFrame implements KeyListener, ActionListener{
private JTextField guess;
private JButton b1;
private void addComponentsToPane(){
b1 = new JButton("New Game");
b1.addActionListener(this);
guess = new JTextField(2);
guess.addKeyListener(this);

稍后在代码中,我使用 keyTyped(KeyEvent ke)JTextFieldactionPerformed(ActionEvent ae) 获取文本输入J 按钮

我的问题是,是否应该使用 documentListener/documentFilter 而不是 keyListener为什么为什么不

最佳答案

  • KeyListener——您几乎永远不要将其与文本组件一起使用,因为它是一个低级结构,可能会扰乱文本组件的功能。
  • DocumentListener——如果您不打算过滤输入——如果您要接受所有呈现的输入但只想跟踪输入,请使用它。
  • DocumentFilter -- 如果您要在显示之前过滤输入,请使用。

我自己会使用 DocumentFilter,因为这样我就可以忽略非字母输入。我也支持 Kevin 提到的所有内容。 1+ 他的回答。

关于java - DocumentListener 或 KeyListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29830788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com