3

我需要在两个(或更多)组合框之间共享数据,但我想独立选择元素。例如,如果我在第一个组合框中选择 Object1,我的第二个 ComboBox 也选择 Object1,因为它们具有相同的模型(DefaultComboBoxModel 并且此模型也管理所选对象)。但我不想要这种行为。我想独立选择组合框中的对象。当我在第一个组合框中选择对象时,我的第二个组合框不应该改变。

此时我正在考虑两个模特的超模。Supermodel 将向子模型发送事件,它们将更新组合框数据,但不更新状态。但我认为这不是最好的方法。

还有更有趣和简单的方法吗?

这是理解我的意思的简短代码:

package hello;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JComboBox;
public class Comboboxes extends JFrame
{
private JPanel contentPane;
public static void main(String[] args)
{
    EventQueue.invokeLater(new Runnable()
    {
        public void run()
        {
            try
            {
                Comboboxes frame = new Comboboxes();
                frame.setVisible(true);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    });
}

public Comboboxes()
{
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JComboBox one = new JComboBox();
    one.setBounds(10, 11, 414, 26);
    contentPane.add(one);

    JComboBox two = new JComboBox();
    two.setBounds(10, 52, 414, 26);
    contentPane.add(two);

    DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
    model.addElement("Item 1");
    model.addElement("Item 2");
    model.addElement("Item 3");

    one.setModel(model);
    two.setModel(model);
}
}
4

1 回答 1

4

Write a decorator for your ComboBoxModel. The decorator should manage the selectedItem property, while everything else is managed by the delegate.

You would then have 1 original model, and place different decorators on the comboboxes:

DefaultComboBoxModel original = ...;

DecoratedModel firstModel = new DecoratedModel( original );
JComboBox firstCombo = new JComboBox( firstModel );

DecoratedModel secondModel = new DecoratedModel( original );
JComboBox secondCombo = new JComboBox( secondModel );

Changes to the data can then be performed on the original model, which will adjust the data in all comboboxes simultaneously

Note: make sure listeners attached to the decorator receive events with the decorated model as source, and not with the delegate model. This is a common mistake when writing a decorator

Edit

An alternative is to have a base data structure which is not a ComboBoxModel and create an implementation of ComboBoxModel which uses that data structure. You can then create different combobox model instances which all share the same data structure.

于 2012-11-19T14:45:33.273 回答