首页 > 解决方案 > 仅使用一种方法重置与 Swing 不同

问题描述

我有几种表格,我想用一种方法重置。我试过这个并且它有效,但我想避免使用 instanceof 链。

reset.addActionListener(e -> Listener.clear(a,b,c,d));

static void clear(JComponent ... fields) throws IllegalArgumentException{
   Stream.of(fields).forEach(Listener::clear);
}

static void clear(JComponent field) throws IllegalArgumentException{
    if(field instanceof JTextComponent a) a.setText("");
    else if(field instanceof DatePicker a) a.setDate(null);
    else if(field instanceof DateTimePicker a) a.setDateTimeStrict(null);
    else if(field instanceof JComboBox a) a.setSelectedIndex(-1);
    else if(field instanceof JSpinner a) a.setValue(1);
    else throw new IllegalArgumentException("Clear not valid");
}

我该如何解决?

标签: javaswinginstanceof

解决方案


推荐阅读