【问题标题】:Select JTree node from JComboBox and vice versa从 JComboBox 中选择 JTree 节点,反之亦然
【发布时间】:2020-05-04 10:57:13
【问题描述】:

我的应用程序中有 JTree 和 JComboBox。当我选择一个节点时,JComboBox 的内容也会改变,但是在选择 JComboBox 项目的情况下我需要做同样的事情。

如您所见,如果我选择“默认会话开始”,则应在 JTree 中选择相同的节点。有人可以告诉我,什么是一个好的方法。 enter image description here

【问题讨论】:

  • 启用模型-视图-控制器范例会将模型(选定节点)保存在控制器中。控制器将更改侦听器添加到视图(树和组合框)(的数据模型)。在侦听器中,如果尚未选择,控制器可以在每个视图中进行选择。
  • 能否提供一些代码示例?

标签: java swing user-interface jcombobox jtree


【解决方案1】:

这只是应用程序框架的一部分。 Swing 相当冗长,您需要解决很多问题。您为 JComponents 提供数据模型,并且需要添加侦听器,或者

JComboBox<Thing> comboBox = new JComboBox<>(controller.getComboBoxModel());

JTree tree = new JComboBox<>();
... tree.setSelectionModel(controller.getTreeSelectionModel());

publi class Controller { // or Application

    public static void main(String[] args) { ... }

    // Model:
    private ComboBoxModel<Thing> comboBoxModel;
    private TreeSelectionModel treeSelectionModel;

    public Controller() {
        comboBoxModel = new DefaultComboBoxModel() {
            @Override
            pubic void setSelectedItem​(Thing item) {
                if (!item.equals(getSelectedItem())) {
                    super.setSelectedItem(itenm);
                    treeSelectionModel.setSelectionPath(...);
                }
            }
        };
        treeSelectionModel = new DefaultTreeSelectionModel ...

        ...
    }

重要的是,对于未更改的项目,没有来回设置所选项目。因此是相等性检验。

【讨论】:

  • 感谢 Joop Eggen 的回答,我已经实现了 Controller 类和集合选择模型,如您的示例所示。有一个问题,当我选择一个节点时,没有调用 setSelectedItem() 方法:)
  • 在组合框中?在树中,您必须寻找 TreePath 的选择。
猜你喜欢
  • 2021-04-07
  • 2014-04-16
  • 2012-07-16
  • 2014-04-05
  • 2019-02-14
  • 1970-01-01
  • 1970-01-01
  • 2010-11-10
  • 2012-03-06
相关资源
最近更新 更多