gpt4 book ai didi

java - 使用具有公共(public)数据源的多个 JComboBox

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:46:34 27 4
gpt4 key购买 nike

我希望能够将多个 JComboBox 与单个公共(public)数据源一起使用。我希望组合框能够显示该列表中的项目或空白项目,最重要的是我希望它们不显示当前被另一个组合框选中的项目(但如果未选中则显示它) .

我一直在尝试通过调用 removeDuplicates() 方法来解决这个问题,该方法应该将所有当前选定的项目添加到列表中,从主列表中删除它,然后将其设置为组合框的列表。

这给我带来了一些有趣的问题。在我的程序中,主列表中的任何选项都没有出现,即使是最初,但如果我摆脱我的代码以删除重复项(初始化测试工作正常),它们就会出现。

此外,即使它们是可编辑的组合框,我也无法向其中写入选定的项目,但只要我按下回车按钮,它就会被删除。

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;

@SuppressWarnings("serial")
public class Main extends JFrame implements ActionListener
{
ArrayList<String> commonItemList = new ArrayList<String>(Arrays.asList("Dog", "Cat", "Fish", "Bear", "Lion"));
ArrayList<JComboBox<Object>> comboBoxes = new ArrayList<>();

public Main()
{
this.setSize(new Dimension(500, 150));
this.setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

JComboBox<Object> comboBox1 = new JComboBox<Object>(commonItemList.toArray());
comboBox1.setEditable(true);
comboBox1.addActionListener(this);

JComboBox<Object> comboBox2 = new JComboBox<Object>(commonItemList.toArray());
comboBox2.setEditable(true);
comboBox2.addActionListener(this);

JComboBox<Object> comboBox3 = new JComboBox<Object>(commonItemList.toArray());
comboBox3.setEditable(true);
comboBox3.addActionListener(this);

this.add(comboBox1);
comboBoxes.add(comboBox1);
this.add(comboBox2);
comboBoxes.add(comboBox2);
this.add(comboBox3);
comboBoxes.add(comboBox3);
}

public static void main(String[] args)
{
Main main = new Main();
main.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent arg0)
{
removeDuplicates();
}

private void removeDuplicates()
{
ArrayList<String> currentlyUsedItems = new ArrayList<>();
ArrayList<String> availableItems = commonItemList;

// Add all currently selected items to usedItems list
for (JComboBox<Object> comboBox : comboBoxes)
{
currentlyUsedItems.add((String) comboBox.getSelectedItem());
}

// For every string in currentlyUsedItems remove it from availableItems
for (String string : currentlyUsedItems)
{
availableItems.remove(string);
}

// Remove all items from combobox, then add back all available Items, while disabling actionListener
for (JComboBox<Object> comboBox : comboBoxes)
{
comboBox.removeActionListener(this);

comboBox.removeAllItems();

for (String string : availableItems)
{
comboBox.addItem(string);
}

comboBox.addActionListener(this);
}
}
}

上面我发布了一个 SSCCE,它与我的问题并不完全相同,但无论如何它仍然存在错误,并且使用了我用来尝试解决我的问题的相同方法。是不是我遗漏了什么,或者这只是一种糟糕的解决方法?

最佳答案

如图here ,对模型而不是 View 进行操作。在这种情况下,不同的模型可以共享对了解这些模型的公共(public)数据源的访问。

关于java - 使用具有公共(public)数据源的多个 JComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24699679/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com