0

我有一个简单的程序,它要求提供一个要连接的 IP 地址、一个用户 ID 和一个密码。IP 地址是通过/输入组合框来选择的。

当用户输入地址并移至另一个字段以输入数据时,将调用验证例程,如果输入的地址无效,组合框背景将变为红色,并显示包含错误消息的标签。

问题是当用户返回到 ip 组合框时,背景颜色仍然是红色。

它没有改变。

我如何编码组合框来克服我的问题?

4

1 回答 1

0

尝试在您的JComboBox上使用FocusListener。使用它,您可以在进入组合框和退出组合框时管理背景颜色。下面是简单的例子:

import java.awt.BorderLayout;
public class Example extends JFrame {

private JComboBox<String> box;

public Example() {
    init();
}

private void init() {
    box = new JComboBox<String>(getObjects());
    box.setBackground(Color.RED);
    box.addFocusListener(getFocusListener());
    JTextField f = new JTextField();
    add(box,BorderLayout.SOUTH);
    add(f,BorderLayout.NORTH);
    pack();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
}

private FocusListener getFocusListener() {
    return new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent arg0) {
            super.focusGained(arg0);
            box.setBackground(Color.BLACK);
            //validate();
        }

        @Override
        public void focusLost(FocusEvent arg0) {
            super.focusLost(arg0);
            box.setBackground(Color.red);
            //validate();
        }
    };

}

private String[] getObjects() {
    return new String[]{"1","22","33"};
}

public static void main(String... s) {
    Example p = new Example();
}

}
于 2013-10-31T06:50:45.830 回答