【问题标题】:how to filter certain characters in JTextField如何过滤 JTextField 中的某些字符
【发布时间】:2013-03-20 04:16:32
【问题描述】:

如何防止用户在“JTextField”中输入某些字符,如果输入了该字符,则不要在文本字段中显示它

【问题讨论】:

  • 不是 DocumentFilter 的问题,KeyListener 只适用于同时按下三个或更多键的快捷键,

标签: java swing jtextfield


【解决方案1】:

您可以使用 JFormattedTextField 或创建自定义 DocumentFilter

【讨论】:

【解决方案2】:
JTextField textField = new JTextField(10);
textField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
  char c = e.getKeyChar();
  if (//Write your condition here) {
     e.consume();  // ignore event
}});

更多关于同一here

【讨论】:

  • -1,您不应该使用 KeyListener。 Swing 有更新更好的 API 来解决这个问题。例如,尝试将文本粘贴到您的文本字段中,看看会发生什么。
  • 使用文档监听器
猜你喜欢
  • 2016-12-08
  • 1970-01-01
  • 2021-02-25
  • 1970-01-01
  • 2021-12-10
  • 2012-06-26
  • 1970-01-01
  • 2012-02-02
  • 1970-01-01
相关资源
最近更新 更多