My goal is to enable a JButton only when some JTextFields and JComboBox change its border color from red to green.
These components are included in three different JPanel.
I try to create a function that reads all components in a JPanel but, when I’m going to compared the colors, the program returns me that I’m casting the variables in a bad way.
Below there’s my function.
Can someone help me?
JavaScript
x
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;
}
Advertisement
Answer
When you change the border of a component, a property listener will be fired. You can register a property listener to the combobox/textfield and enable/disable the button according to the new border.
An example:
JavaScript
@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.");
}