IconProperty extends OptionalProperty<Icon> implements PropertyChangeListener { @NotNull @Override public Optional<Icon> get() { if (myComponent instanceof JLabel) { return Optional.ofNullable(((JLabel)myComponent).getIcon()); } else if (myComponent instanceof AbstractButton) { return Optional.ofNullable(((AbstractButton)myComponent).getIcon()); } else { throw new IllegalStateException("Unexpected icon component type: " + myComponent.getClass().getSimpleName()); } } IconProperty(@NotNull JLabel label);  IconProperty(@NotNull AbstractButton button); @Override void propertyChange(PropertyChangeEvent propertyChangeEvent); @NotNull @Override Optional<Icon> get();  }
@Test public void iconPropertyCanWrapLabel() throws Exception { JLabel label = new JLabel(); Icon dummyIcon = new DummyIcon(); IconProperty iconProperty = new IconProperty(label); CountListener listener = new CountListener(); iconProperty.addListener(listener); assertThat(iconProperty.get().isPresent()).isFalse(); assertThat(listener.getCount()).isEqualTo(0); label.setIcon(dummyIcon); assertThat(iconProperty.get().isPresent()).isTrue(); assertThat(iconProperty.getValue()).isEqualTo(dummyIcon); assertThat(listener.getCount()).isEqualTo(1); label.setIcon(null); assertThat(iconProperty.get().isPresent()).isFalse(); assertThat(listener.getCount()).isEqualTo(2); }
@Test public void iconPropertyCanWrapButton() throws Exception { JButton button = new JButton(); Icon dummyIcon = new DummyIcon(); IconProperty iconProperty = new IconProperty(button); CountListener listener = new CountListener(); iconProperty.addListener(listener); assertThat(iconProperty.get().isPresent()).isFalse(); assertThat(listener.getCount()).isEqualTo(0); button.setIcon(dummyIcon); assertThat(iconProperty.get().isPresent()).isTrue(); assertThat(iconProperty.getValue()).isEqualTo(dummyIcon); assertThat(listener.getCount()).isEqualTo(1); button.setIcon(null); assertThat(iconProperty.get().isPresent()).isFalse(); assertThat(listener.getCount()).isEqualTo(2); }