某些组件更改其边框颜色时启用JButton

问题描述

我的目标是仅在某些JTextField和JComboBox将其边框颜色从红色更改为绿色时启用JButton。
这些组件包含在三个不同的JPanel中。
我尝试创建一个读取JPanel中所有组件的函数,但是,当我要比较颜色时,程序返回我说我以一种不好的方式转换了变量。
下面是我的功能。
有人可以帮我吗?

    public static boolean countBoards(JPanel panel){
        boolean red = false;
        
        for(Component control : panel.getComponents())
        {
            if(control instanceof JTextField)
            {
                JTextField ctrl = (JTextField) control; 
                Color lineColor = ((LineBorder)ctrl.getBorder()).getLineColor();
            
                if(lineColor.equals(Color.red))
                    red = true;                
            }  
            else if(control instanceof JComboBox)
            {
                JComboBox ctr = (JComboBox) control; 
                Color lineColor = ((LineBorder)ctr.getBorder()).getLineColor();
            
                if(lineColor.equals(Color.red))
                    red = true;               
            }
        }                 
        
        return red;
    }

解决方法

当您更改组件的边框时,将触发属性侦听器。您可以将属性侦听器注册到组合框/文本字段,然后根据新边框启用/禁用按钮。

一个例子:

@Test
public void test() {
    JButton myButton = new JButton();
    JComboBox<String> combo = new JComboBox<>();
    combo.addPropertyChangeListener("border",e -> {
        if (e.getNewValue() != null && e.getNewValue() instanceof LineBorder) {
            LineBorder border = (LineBorder) e.getNewValue();
            myButton.setEnabled(border.getLineColor().equals(Color.green));
        }
    });
    assertTrue(myButton.isEnabled(),"Button should be initially enabled.");

    combo.setBorder(BorderFactory.createLineBorder(Color.red));
    assertFalse(myButton.isEnabled(),"Button should be disabled when red line border occurs.");

    combo.setBorder(BorderFactory.createLineBorder(Color.green));
    assertTrue(myButton.isEnabled(),"Button should be enabled when green line border occurs.");
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...