如何解决某些组件更改其边框颜色时启用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.");
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。