简体   繁体   English

Java Swing:启用/禁用特定类型的组件

[英]Java Swing: Enabling/Disabling specific type of components

I need to enable/disable some components inside a JFrame. 我需要启用/禁用JFrame中的某些组件。 But i only want to disable these types: 但是我只想禁用这些类型:

JTextField
JButton
JComboBox

Is there any simple example about doing that kind of things in java? 有没有关于在Java中执行此类操作的简单示例?

Loop through all the components of the JFrame, including components inside other components, and do an instanceof check to see if it's one of the types you want to disable, if so, disable the component. 遍历JFrame的所有组件,包括其他组件内部的组件,并执行instanceof检查以查看它是否是要禁用的类型之一,如果是,请禁用该组件。

As an example on how to do this, one could enable or disable all JButtons with the following function : 作为有关如何执行此操作的示例,可以使用以下功能启用或禁用所有JButton:

public void flipEnabledOnAllButtons(boolean enabled, Container rootContainerToSearch)
{    
    for (Component c : rootContainerToSearch.getComponents())    
    {    
        if (c instanceof Container)    
        {    
            flipEnabledOnAllButtons(enabled, (Container)c);    
        }    

        if (c instanceof JButton)    
        {    
            c.setEnabled(enabled);    
        }      
    }
}

Check out Darryl's Swing Utils . 查看Darryl的Swing Utils You can use the class to get a List of components of a specific class. 您可以使用该类来获取特定类的组件列表。 Then you iterate through the list to do your processing. 然后,您遍历列表进行处理。

Ro example to get al the combo box compnents you could uee: 举例来说,您可以使用组合框组件:

List<JComboBox> components = SwingUtils.getDescendantsOfType(JComboBox.class, frame.getContentPane(), true);

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

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