java if 语句在 if(item instanceof nomclass) 中不起作用

标签 java instanceof

我刚刚为我的保存按钮编写了一个actionPerformed,它将数据保存到数组列表中,但在此之前我必须确保所有字段都不为空,因此如果文本字段为空,我想显示一个对话框并将所有字段都为空红色背景颜色的文本字段

这是我的代码

//Field outside constructor
private List<Component> comp;





//inside constructor
comp = getAllComponents(this);
//method
public static List<Component> getAllComponents(final Container c) {
    Component[] comps = c.getComponents();
    List<Component> compList = new ArrayList<Component>();
    for (Component comp : comps) {
        compList.add(comp);
        if (comp instanceof Container)
            compList.addAll(getAllComponents((Container) comp));
    }
    return compList;
}

``

//actionperformed
if(e.getSource() == savebtn){
        for(Component item:comp){
            if(item.isVisible()){
                if(item instanceof JTextField){
                    JTextField txtField = (JTextField)item;
//here is my problem: with no if statement my program works fine and puts all textfields in red but I want to highlight just empty textfields;
                    if(txtField.getText() == null)
                    txtField.setBackground(Color.RED);
                }
            }
        }


    }

那么我该如何解决这个问题呢?非常感谢

最佳答案

if(txtField.getText() == null)

这里不检查是否为空,参见 public String getText()1 的文档:

Returns the text contained in this TextComponent. If the underlying document is null, will give a NullPointerException. Note that text is not a bound property, so no PropertyChangeEvent is fired when it changes. To listen for changes to the text, use DocumentListener.

我会使用DocumentListener相反,类似的东西:

myTextField.getDocument().addDocumentListener(new DocumentListener() {

    public void changedUpdate(DocumentEvent e) { checkIfEmpty(); }
    public void removeUpdate(DocumentEvent e) { checkIfEmpty(); }
    public void insertUpdate(DocumentEvent e) { checkIfEmpty();}

    public void checkIfEmpty() {
       if (myTextField.getText().equals("")){
           //set color to red
       } else {
           //set color back
       }   
    }
});

1 另请注意该方法的签名,它返回一个 String

关于java if 语句在 if(item instanceof nomclass) 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27224057/

相关文章:

JSF EL : instanceof reserved but not yet implemented?

javascript - 如何检查实例的构造函数

java - Java 中的 instanceof - 为什么不能编译?

java - Porter Stemmer 和 Weka

java - java中内部类访问外部类

java - 文件名存疑

java - java中的简单 Controller Rest端点测试

java - 相当于instanceof

java - 在这种情况下替代 instanceof 方法

java - 文档显示架构问题