简体   繁体   English

如何将getSource()转换为JTextField?

[英]How to cast getSource() to be a JTextField?

I am making a KeyListener class so I can control any JTextField that I want, but I do not know how to get whatever JTextField I call so I can press escape and clear the JTextField ? 我正在制作KeyListener类,以便可以控制所需的任何JTextField ,但是我不知道如何获取要调用的JTextField因此可以按JTextField键并清除JTextField吗? Here is my current code 这是我当前的代码

private class IntegerTxtListener implements KeyListener {
    public void keyTyped(final KeyEvent e) {
            if (e.getKeyChar() < KeyEvent.VK_0
                    || e.getKeyChar() > KeyEvent.VK_9) {
                e.consume();
            }
        if (e.getKeyChar() == KeyEvent.VK_ESCAPE) {
            e.consume();
           //My Problem is Here----------------------------
            e.getSource()).setText("");
        }
    }

    @Override
    public void keyPressed(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }
}

It looks like, to me, you are trying to create a text field that only allows integer values. 在我看来,您似乎正在尝试创建一个仅允许整数值的文本字段。 First of all, you shouldn't be using a KeyListener for a JTextField . 首先,您不应该为JTextField使用KeyListener Instead you should be using a DocumentFilter for the underlying document of the JTextField . 相反,您应该对JTextField的基础文档使用DocumentFilter The DocumentFilter can filter out any unwanted input. DocumentFilter可以过滤掉任何不需要的输入。

Here is an example of a JTextField that only allows integer input. 这是仅允许整数输入的JTextField的示例。

private JTextField createTextField() {
    JTextField field = new JTextField();
    ((AbstractDocument) field.getDocument()).setDocumentFilter(new DocumentFilter() {
        @Override
        public void insertString(FilterBypass fb, int off, String str, AttributeSet attr)
                throws BadLocationException {
            fb.insertString(off, str.replaceAll("\\D++", ""), attr);  // remove non-digits
        }

        @Override
        public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr)
                throws BadLocationException {
            fb.replace(off, len, str.replaceAll("\\D++", ""), attr);  // remove non-digits
        }
    });
    return field;
} 

Also, may be unrelated, but another listener you may want to look into, dealing with text input is a DocumentListener , that will listener for changes in the underlying document of the text field. 同样,可能没有关系,但是您可能要研究的另一个侦听器(用于处理文本输入)是DocumentListener ,它将侦听文本字段的基础文档中的更改。 You can read more at How to write DocumentListeners 您可以在如何编写DocumentListeners中阅读更多内容

I don't know what are you trying to achieve but if it is about to control user input consider using a DocumentFilter instead. 我不知道您要达到什么目的,但是如果要控制用户输入,请考虑使用DocumentFilter

If you still want to use a KeyListener just cast e.getSource() to JTextField , to ensure to don't have a ClassCastException you should use instanceof operator like example below. 如果您仍想使用KeyListener只需将e.getSource()JTextField ,以确保没有ClassCastException ,则应使用instanceof运算符,例如下面的示例。

if(evt.getSource() instanceof JTextField){
   JTextField textfield = (JTextField) e.getSource();
   textfield.setText("..");
   e.consume();
}

Consider extends KeyAdapter rather than implementing KeyListener . 考虑扩展KeyAdapter而不是实现KeyListener

I think this schould work: 我认为这应该工作:

if (e.getKeyChar() == KeyEvent.VK_ESCAPE) {
    e.consume();
   //My Problem is Here----------------------------
    ((JTextField)e.getSource()).setText("");
}

Just the default way of casting objects. 只是投射对象的默认方式。

But it might happen that some errors occur if e is not an instance of JTextField . 但是 ,如果e不是JTextField的实例,则可能会发生一些错误。
So if you are sure that your Listener will not give a source other than JTextField object you can go this way. 因此,如果您确定侦听器不会提供JTextField对象以外的其他源,则可以采用这种方式。 Otherwise you you add errorhandling /-prevention. 否则,您将添加错误处理/-预防。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ActionEvent.getSource:如何正确转换源对象 - ActionEvent.getSource: how to cast properly the source Object 为什么在使用 .getSource() 方法时将 ChangeEvent 对象转换为 JSlider? - Why cast a ChangeEvent object to JSlider when using .getSource() Method? 如何在ActionListener中将.getSource()与多个JButton一起使用 - How to use .getSource() with multiple JButtons in ActionListener 为什么ChangeListener的getSource()不返回用于生成事件的类型的预制对象? - Why doesn't ChangeListener's getSource() return a pre-cast object of the type used to generate an event? 如何从其他类制作的按钮对象中获取源代码 - How to getSource from a button object made from other class' 无法弄清楚如何从另一个类使用getSource - Cannot figure out how to use getSource from another class 如何使用e.getSource()为按钮编写“计数”? - How to write a 'count' for buttons using e.getSource()? GetSource? 如何在数组中保存按钮的位置? (网格布局) - GetSource? How to save the Location of a button in an Array? (Grid-layout) 如何将JTextField转换为String并将String转换为JTextField? - How to convert JTextField to String and String to JTextField? 如何在其他JTextField下找到JTextField? - How to locate JTextField under other JTextField?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM