如何更改具有相同索引-java的两个组合框的项目?

时间:2016-09-24 19:39:10

标签: java swing netbeans combobox

我有两个组合框,一个用于选择'数字'另一个用于选择' name'。当我从数字中选择一个项目时,必须根据数字索引更改名称,反之亦然。

Click here to see image

 private void nameItemStateChanged(java.awt.event.ItemEvent evt) 
    {                                                
         int i = name.getSelectedIndex();
         number.setSelectedIndex(i);
        //It will changes number according to name  
        //Used ItemEvent        
    }  



private void numberItemStateChanged(java.awt.event.ItemEvent evt) 
   {                                                
         int i = number.getSelectedIndex();
         name.setSelectedIndex(i);
         //It will change name according to number
         //used ItemEvent
    }  

这些代码正在制作例外,因为两者都在使用ItemStateChanged事件。所以建议另一种方法..

1 个答案:

答案 0 :(得分:1)

您似乎正在为您的类提供两个具有相同签名的方法,并且编译将不允许您执行此操作。如果是这样,那么解决方案就是不这样做。如果你绝对需要两个以一对一的关系紧密绑在一起的JComboBox,那些我推荐你做的事情,那么要么给每个组合框自己的ChangeListener,要么更好,让他们共享相同的模型,但每个使用不同的渲染器。

如需更具体的答案,请更新您的问题,包括发布有效的minimal example programSSCCE(请查看相关链接)。

例如,这里有两个共享相同模型的JComboBox,一个包含“Customer”对象的模型。 Customer类只有两个私有实例字段,一个int“id”字段和一个String“name”字段。因此,两个组合框再次保持相同数据。

但是它们通过使用不同的单元格渲染器来显示数据,一个只显示id,另一个只显示名称。您只需要将ChangeListener添加到一个,如果更改了组合框的选择,它将被激活,因为更改组合框会改变另一个组合(同样它们共享相同的模型)。

import java.awt.Component;
import java.awt.event.ItemEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class LinkedComboEg extends JPanel {
    private DefaultComboBoxModel<Customer> comboModel = new DefaultComboBoxModel<>();
    private JComboBox<Customer> idCombo = new JComboBox<>(comboModel);
    private JComboBox<Customer> nameCombo = new JComboBox<>(comboModel);

    public LinkedComboEg() {
        comboModel.addElement(new Customer(1001, "Doc"));
        comboModel.addElement(new Customer(1002, "Donald Trump"));
        comboModel.addElement(new Customer(1003, "Bashful"));
        comboModel.addElement(new Customer(1004, "Grumpy"));
        comboModel.addElement(new Customer(1005, "Sneezy"));
        comboModel.addElement(new Customer(1006, "Happy"));
        comboModel.addElement(new Customer(1007, "Sleepy"));

        idCombo.setRenderer(new IdRenderer());
        nameCombo.setRenderer(new NameRenderer());
        nameCombo.setSelectedIndex(-1); // none selected to start

        // add an item listener to just one combo box. Either will do
        idCombo.addItemListener(ie -> {
            Customer selection = (Customer) ie.getItem();
            if (ie.getStateChange() == ItemEvent.SELECTED && selection != null) {
                System.out.printf("Selected id: %s;   Selected name: %s%n", 
                        selection.getId(),
                        selection.getName());
            }
        });

        add(new JLabel("ID Number:"));
        add(idCombo);
        add(Box.createHorizontalStrut(20));
        add(new JLabel("Name:"));
        add(nameCombo);
    }

    // renderer to add to the idCombo so that it displays the Customer's ID
    private class IdRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {
            if (value == null) {
                value = "";
            } else {
                value = ((Customer) value).getId();
            }
            return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        }
    }

    // renderer to add to the nameCombo so that it displays the Customer's Name
    private class NameRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {
            if (value == null) {
                value = "";
            } else {
                value = ((Customer) value).getName();
            }
            return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        }
    }

    private static void createAndShowGui() {
        LinkedComboEg mainPanel = new LinkedComboEg();

        JFrame frame = new JFrame("Linked Combo Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

public class Customer {
    private int id;
    private String name;

    public Customer(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Customer other = (Customer) obj;
        if (id != other.id)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

}