Java - 格式化整个表单上的字段

时间:2017-10-10 02:27:05

标签: java

Java新手......为练习创建基本形式。我有一个包含10个以上文本框的表单,我希望格式化为用户进入字段时变为青色,并在离开字段时返回白色。如果文本被编辑,它将变为红色,以向用户显示他们所在的字段以及他们已编辑的文本。

我的代码正在运行,但是,我必须为每个文本框复制此Focus Listener和Modify Listener代码,或者有没有办法为表单上的所有文本框设置“默认”?

text_8 = new Text(shell, SWT.BORDER);
    text_8.addFocusListener(new FocusAdapter() {            @Override
        public void focusGained(FocusEvent e) {
            text_8.setBackground(SWTResourceManager.getColor(SWT.COLOR_CYAN));
        }
        @Override
        public void focusLost(FocusEvent e) {
            text_8.addModifyListener(new ModifyListener() {
                public void modifyText(ModifyEvent e) {
                    text_8.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));                   
                }
            });
            text_8.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
        }
    });
    text_8.setBounds(10, 341, 76, 21);

1 个答案:

答案 0 :(得分:0)

嗯,最简单的方法是将这些侦听器提取到单独的变量中,然后只添加到你想要的每个组件......

尝试这样的事情:

private static class MyListeners implement ModifyListener extends FocusAdapter
{
   @Override
   public void focusGained(FocusEvent e)
   {
      final Text t = (Text) e.source;
      t.setBackground(SWTResourceManager.getColor(SWT.COLOR_CYAN));
      t.addModifyListener(this);
   }
   @Override
   public void focusLost(FocusEvent e)
   {
      final Text t = (Text) e.source;
      t.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
      t.removeModifyListener(this);
   }
   public void modifyText(ModifyEvent e)
   {
      final Text t = (Text) e.source;
      t.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));                   
   }
}
private final MyListeners myListeners = new MyListeners();

...

text_8 = new Text(shell, SWT.BORDER);
text_8.addFocusListener(myListeners);
text_8.setBounds(10, 341, 76, 21);