【问题标题】:Java Key Listener not workingJava 密钥侦听器不起作用
【发布时间】:2013-12-16 12:40:57
【问题描述】:

试图让文本字段只接受整数

它如何消耗我在字段中输入的所有内容,或者它只是让输入任何内容 这很简单,这就是为什么很难找到问题的原因。

JLabel year = new JLabel("Year:");
      final JTextField yeart = new JTextField(10);
      yeart.addKeyListener(new KeyAdapter()
      {
         @Override
         public void keyTyped(KeyEvent e)
         {
            super.keyTyped(e);

            e.getKeyCode();

            if (!(e.getKeyCode() >= 48 || e.getKeyCode() <= 57))
            {
               e.consume();
            }
         }



      });

【问题讨论】:

  • 以后,请将您使用的编程语言作为标签添加到您的问题中,这将有助于更多人找到您的问题,从而帮助他们更快地得到答案。
  • 发布SCCEE 会让您获得更好的结果。
  • 在使用JTextComponent 实例时使用DocumentListenerDocumentFilter,而不是KeyListener。例如,复制粘贴会破坏您的功能。除此之外,您也可以为此使用JFormattedTextField(参见here 示例)
  • 如果我能做到这一点,我为什么要使用 DocumentListenet 或 DocumentFilter?这更容易理解和解释。
  • @FancyPants 如果我能完成这项工作。我是说您不能:例如,复制粘贴或拖放不适用于您的 KeyListener

标签: java swing user-interface keylistener


【解决方案1】:

使用 && 代替 ||。 (!(e.getKeyCode() >= 48 || e.getKeyCode()

【讨论】:

  • 添加了 && ,现在它不允许我输入任何内容。
  • 使用 if (!((int)e.getKeyChar() >= 48 && (int)e.getKeyChar()
  • @FancyPants, Works now - 尝试将文本粘贴到文本字段中。
猜你喜欢
  • 1970-01-01
  • 2013-04-30
  • 2022-10-17
  • 2017-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多