Возможно ли как-то иметь два основных вида и один подробный вид?

Если у меня есть, например, один главный вид слева и один посередине, каждый из которых показывает oder Java Beans/POJO, могу ли я использовать общий подробный вид, который каким-то образом прослушивает активные bean-компоненты каждого представления, а затем отображает текущий выбранный в более детально? Отношение один к одному довольно легко управлять с помощью вашей библиотеки контекста.

@ViewDocking(areaId ="left", position=1, displayName="Profiles", menuEntry = @WindowMenuEntry(path = "", position=0), accelerator="Shortcut+1")
public class ProfileListView extends BorderPane implements LocalContextProvider {

private final SimpleContextContent content = new SimpleContextContent();

private final SimpleContext context = new SimpleContext(content);

@FXML
private ListView<Profile> listview;

public ProfileListView() {
    load();
    // add some profiles
    listview.getItems().add(new Profile("Profile1"));
    listview.getItems().add(new Profile("Profile2"));
    listview.getItems().add(new Profile("Profile3"));

    // setup selection listener
    listview.getSelectionModel().selectedItemProperty().addListener((value, oldProfile, newProfile) -> {
        // set active profile and remove old one
        content.remove(oldProfile);
        content.add(newProfile);
    });

    // setup double click listener
    configureClickListener();
}

private Profile getSelectedProfile() {
    return listview.getSelectionModel().getSelectedItem();
}

private void configureClickListener() {
    listview.setOnMouseClicked(event -> {
        // check if it was a double click
        if(event.getClickCount() == 2) {
            System.out.println(getSelectedProfile());
            // inject into editor pane
            // calls the procedure to create a tab in the center area...
        }
    });
}

private void load() {
    FXMLLoaders.loadRoot(this);
}

@Override
public Context getLocalContext() {
    return context;
}
}

Это один основной вид, содержащий представление списка элементов. Другая будет та же самая, закрепленная справа от другой вкладки и содержащая POJO типа "Действие".

Подробный вид здесь:

@ViewDocking(areaId = "right", displayName = "Properties", accelerator = "Shortcut+2", menuEntry = @WindowMenuEntry(path = "", position = 0), position = 1)
public class ProfilePropertiesView extends BorderPane implements LocalContextProvider, ActiveContextSensitive {

private Context activeContext;

private SimpleContextContent content = new SimpleContextContent();

private SimpleContext context = new SimpleContext(content);

private Profile profile;

private IWindowService service = new NullWindowService();

@FXML
private PropertySheet propertysheet;

public ProfilePropertiesView() {
    load();
    // retrieve framework service, TODO: use tracker
    BundleContext ctx = FrameworkUtil.getBundle(getClass()).getBundleContext();
    service = ctx.getService(ctx.getServiceReference(IWindowService.class));
    // initialize callback
    service.addCallback(title -> {
        System.out.println("callback called " + title);
        // update the property sheet ui by re-creating the items list
       // updateUI();
        // we can safely return null
        return null;
    });

    // configure editor factory so the user is able to use a combobox
    propertysheet.setPropertyEditorFactory(new CustomPropertyEditorFactory(service));
}

private void load() {
    FXMLLoaders.loadRoot(this);
}

@Override
public Context getLocalContext() {
    return context;
}

private void contextChanged() {
    // find profile information
    Profile found = activeContext.find(Profile.class);
    // if the found profile is null, ignore it
    if (found != null) {
        // reset if profile is valid
        if (profile != null) {
            reset();
        }
        // create reference and register
        profile = found;
        register();
    }
}

private void register() {
    // retrieve observablelist of bean properties if some profile is selected
    if(profile != null) {
        ObservableList<Item> items = createDetailedList(profile);
        propertysheet.getItems().setAll(items);
    }
}

private void updateUI() {
    // clear property elements and re-create them
    reset();
    // re-create items
    ObservableList<Item> items = createDetailedList(profile);
    propertysheet.getItems().addAll(items);
}

private ObservableList<Item> createDetailedList(Object bean) {
    ObservableList<Item> list = FXCollections.observableArrayList();
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
        Arrays.stream(beanInfo.getPropertyDescriptors()).map(pd -> new DetailedBeanProperty(bean, pd)).forEach(list::add);
    } catch (IntrospectionException e) {
        e.printStackTrace();
    }

    return list;
}

private void reset() {
    propertysheet.getItems().clear();
}

@Override
public void setActiveContext(Context activeContext) {
    this.activeContext = activeContext;
    this.activeContext.addContextListener(Profile.class, event -> contextChanged());
    // trigger change
    contextChanged();
}
}

Текущий ProfilePropertiesView просто настроен для отображения свойств выбранного профиля. Я хочу, чтобы он мог отображать текущую информацию о последнем выбранном POJO в пользовательском интерфейсе. Это означает, что если пользователь выбрал профиль из ListView, этот профиль должен отображаться в представлении свойств. Если он выбрал действие из таблицы (которая отображается в центре), свойства действия должны отображаться.

1 ответ

Нужно ли просто зарегистрировать новый ContextListener для POJO класса Action.class, а затем вызвать метод для заполнения PropertiesView? Я не был уверен, что это правильное решение...

Да, просто добавьте еще один ContextListener в activeContext для каждого типа POJO, который вы хотите наблюдать.

Также обратите внимание, что в конструкторе представлений лучше использовать ServiceTracker, а не искать сервис через BundleContext, так как сервис может быть еще недоступен, в зависимости от порядка загрузки пакетов.

Вы можете найти образец, который использует ServiceTracker здесь: /questions/15770904/kak-mne-ispolzovat-servis-osgi-v-doke/15770912#15770912

Другие вопросы по тегам