在 JList 中有一个预选选项

Having a preselected option in a JList

背景:

我正在为邮轮公司创建 GUI。系统的用户可以执行以下任务:使用 GUI 添加新的船只、甲板、船舱和游轮。

问题:

在我的系统中,我添加了复制游轮的功能,因此一旦选择了要复制的游轮,就会打开一个单独的框架,其中预先填充了从中复制的游轮的数据从。但是,打开的单独框架(我们称之为 "duplicate cruise frame"),该框架还有一个 JList,用于将一艘船分配给巡航。

问题:

我需要重复的巡航框架中的 JList 才能让分配给它的船在 JList 中突出显示。

例如,如果我有以下数据的游轮:

SHIP NAME: Pegasus
START PORT: Oban
END PORT: Teran
ASSIGNED TO SHIP: Scottie

单击 "duplicate" 按钮后,我希望重复巡航框架中的 JList 已经突出显示:ASSIGNED TO SHIP: Scottie

代码片段:

这是 JList,它包含有关 Ships(一组船只)的数据:

JScrollPane scrollPane2 = new JScrollPane();
shipList = new JList(fleet.getShips().toArray());
scrollPane2.setViewportView(shipList);
shipList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
shipList.setVisibleRowCount(4);
southPanel.add(scrollPane2);
wholeFramePanel2.add(southPanel);
addCruiseF.add(wholeFramePanel2);
addCruiseF.setVisible(true);

我试过的:

shipList.setSelectedIndex(shipList.getSelectedIndex());

和...

for (int i = 0; i < model.getSize(); i++) {
     Object o = model.getElementAt(i);
     if(o.equals(cruise.getShip())){
       shipList.ensureIndexIsVisible(shipList.getSelectedIndex());
      shipList.setSelectedIndex(i);  
                }
            }

尽管上述两种方法似乎都没有突出邮轮分配给的船只。我该怎么做?

这当然什么都不做:

shipList.setSelectedIndex(shipList.getSelectedIndex());

因为您正在尝试 select 列表 selection 来自 same unselected JList。这是正确的想法,但您需要使用 original JList 中的 selection 索引。您将如何执行此操作的具体细节取决于您的程序的结构,但我敢打赌您将能够弄清楚这一点。