简体   繁体   English

当第一个为空时,java netbeans禁用另一个jFormattedTextField

[英]java netbeans disable another jFormattedTextField when the first one is empty

I'm using jFormattedTextField because it can be easily formatted as I want rather than jTextField. 我正在使用jFormattedTextField,因为它可以轻松地按我的意愿进行格式化,而不是jTextField。 I allow only number as input. 我只允许数字作为输入。

Case: 案件:

I have two jFormattedTextfield forms, let's say they are txtA and txtB, txtB is disabled. 我有两种jFormattedTextfield形式,假设它们是txtA和txtB,而txtB被禁用。

When txtA is empty, txtB always be disabled. 如果txtA为空,则始终禁用txtB。 Otherwise, when txtA isn't empty, txtB will be enabled. 否则,当txtA不为空时,将启用txtB。

If I delete all input in txtA, txtB should be disabled. 如果删除txtA中的所有输入,则应禁用txtB。

I put the code in KeyReleased event. 我将代码放入KeyReleased事件中。 Here is the piece of code: 这是一段代码:

private void txtAKeyReleased(java.awt.event.KeyEvent evt) {                                 
        if(!(txtA.getText().equals(""))){
            int as = txtA.getText().length(); 
            if(as > 0){
                txtB.setEnabled(true);
            }
            else{
                txtB.setEnabled(false); 
            }
        }
        else {
            txtB.setText(null); 
            txtB.setEnabled(false); 
        }
    } 

At a glance, it works. 一眼就能看出来。 But, it doesn't work perfectly. 但是,它并不完美。

When I typed something in txtA, txtB is enabled. 当我在txtA中输入内容时,将启用txtB。

Problem 1: But, if I delete all inputs in txtA, txtB still enable. 问题1:但是,如果我删除txtA中的所有输入,则txtB仍然启用。

Problem 2: txtA should detect only number as input then txtB is enabled. 问题2:txtA应该仅检测数字作为输入,然后启用txtB。 But, when I typed letter or space in txtA, txtB still enable. 但是,当我在txtA中键入字母或空格时,txtB仍然启用。

Surprisingly, when I tried it in JTextField, it works perfectly (txtB disabled when txtA is empty). 令人惊讶的是,当我在JTextField中尝试使用它时,它可以完美工作(当txtA为空时,禁用txtB)。

What should I do to fix this? 我应该怎么做才能解决这个问题?

I put the code in KeyReleased event. 我将代码放入KeyReleased事件中。

Don't use a KeyListener. 不要使用KeyListener。

Instead you should be using a DocumentListener . 相反,您应该使用DocumentListener It will fire an event whenever a change is made to the Document. 每当对文档进行更改时,它将触发一个事件。 Read the section from the Swing tutorial on How to Write a Document Listener for more information and examples. 阅读Swing教程中有关如何编写文档侦听器的部分, 获取更多信息和示例。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM